mirror of
https://github.com/NixOS/nix
synced 2025-06-25 06:31:14 +02:00
nix-util: Add concatMapStrings
This commit is contained in:
parent
bbdc3197a9
commit
f3dbaa3f54
2 changed files with 50 additions and 0 deletions
|
@ -80,6 +80,42 @@ TEST(concatStringsSep, buildSingleString)
|
|||
ASSERT_EQ(concatStringsSep(",", strings), "this");
|
||||
}
|
||||
|
||||
TEST(concatMapStringsSep, empty)
|
||||
{
|
||||
Strings strings;
|
||||
|
||||
ASSERT_EQ(concatMapStringsSep(",", strings, [](const std::string & s) { return s; }), "");
|
||||
}
|
||||
|
||||
TEST(concatMapStringsSep, justOne)
|
||||
{
|
||||
Strings strings;
|
||||
strings.push_back("this");
|
||||
|
||||
ASSERT_EQ(concatMapStringsSep(",", strings, [](const std::string & s) { return s; }), "this");
|
||||
}
|
||||
|
||||
TEST(concatMapStringsSep, two)
|
||||
{
|
||||
Strings strings;
|
||||
strings.push_back("this");
|
||||
strings.push_back("that");
|
||||
|
||||
ASSERT_EQ(concatMapStringsSep(",", strings, [](const std::string & s) { return s; }), "this,that");
|
||||
}
|
||||
|
||||
TEST(concatMapStringsSep, map)
|
||||
{
|
||||
std::map<std::string, std::string> strings;
|
||||
strings["this"] = "that";
|
||||
strings["1"] = "one";
|
||||
|
||||
ASSERT_EQ(
|
||||
concatMapStringsSep(
|
||||
", ", strings, [](const std::pair<std::string, std::string> & s) { return s.first + " -> " + s.second; }),
|
||||
"1 -> one, this -> that");
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------------------
|
||||
* dropEmptyInitThenConcatStringsSep
|
||||
* --------------------------------------------------------------------------*/
|
||||
|
|
|
@ -55,6 +55,20 @@ extern template std::string concatStringsSep(std::string_view, const std::list<s
|
|||
extern template std::string concatStringsSep(std::string_view, const std::set<std::string> &);
|
||||
extern template std::string concatStringsSep(std::string_view, const std::vector<std::string> &);
|
||||
|
||||
/**
|
||||
* Apply a function to the `iterable`'s items and concat them with `separator`.
|
||||
*/
|
||||
template<class C, class F>
|
||||
std::string concatMapStringsSep(std::string_view separator, const C & iterable, F fn)
|
||||
{
|
||||
std::vector<std::string> strings;
|
||||
strings.reserve(iterable.size());
|
||||
for (const auto & elem : iterable) {
|
||||
strings.push_back(fn(elem));
|
||||
}
|
||||
return concatStringsSep(separator, strings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ignore any empty strings at the start of the list, and then concatenate the
|
||||
* given strings with a separator between the elements.
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue