Skip to content

Commit

Permalink
Fix joinToString with initial empty string.
Browse files Browse the repository at this point in the history
  • Loading branch information
kring committed Apr 5, 2024
1 parent 1a6b1f8 commit 3d7ff14
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 18 deletions.
27 changes: 9 additions & 18 deletions CesiumUtility/include/CesiumUtility/joinToString.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,17 @@ namespace CesiumUtility {
template <class TIterator>
std::string
joinToString(TIterator begin, TIterator end, const std::string& separator) {
if (begin == end)
return std::string();

std::string first = *begin;

return std::accumulate(
begin,
++begin,
end,
std::string(),
std::move(first),
[&separator](const std::string& acc, const std::string& element) {
if (!acc.empty()) {
return acc + separator + element;
} else {
return element;
}
return acc + separator + element;
});
}

Expand All @@ -41,16 +42,6 @@ joinToString(TIterator begin, TIterator end, const std::string& separator) {
*/
template <class TCollection>
std::string joinToString(TCollection collection, const std::string& separator) {
return std::accumulate(
collection.cbegin(),
collection.cend(),
std::string(),
[&separator](const std::string& acc, const std::string& element) {
if (!acc.empty()) {
return acc + separator + element;
} else {
return element;
}
});
return joinToString(collection.cbegin(), collection.cend(), separator);
}
} // namespace CesiumUtility
22 changes: 22 additions & 0 deletions CesiumUtility/test/TestJoinToString.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#include <CesiumUtility/joinToString.h>

#include <catch2/catch.hpp>

using namespace CesiumUtility;

TEST_CASE("joinToString") {
CHECK(
joinToString(std::vector<std::string>{"test", "this"}, "--") ==
"test--this");
CHECK(
joinToString(std::vector<std::string>{"test", "this", "thing"}, " ") ==
"test this thing");
CHECK(
joinToString(std::vector<std::string>{"test", "this", "thing"}, "") ==
"testthisthing");
CHECK(joinToString(std::vector<std::string>{"test"}, "--") == "test");
CHECK(joinToString(std::vector<std::string>{""}, "--") == "");
CHECK(joinToString(std::vector<std::string>{"", "aa", ""}, "--") == "--aa--");
CHECK(joinToString(std::vector<std::string>{"", ""}, "--") == "--");
CHECK(joinToString(std::vector<std::string>{}, "--") == "");
}

0 comments on commit 3d7ff14

Please sign in to comment.