mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-21 23:20:20 +00:00
AK: Add String::join
This commit is contained in:
parent
79aaa2fe0f
commit
cccaa94767
Notes:
sideshowbarker
2024-07-17 08:27:05 +09:00
Author: https://github.com/trflynn89 Commit: https://github.com/SerenityOS/serenity/commit/cccaa94767 Pull-request: https://github.com/SerenityOS/serenity/pull/17206 Reviewed-by: https://github.com/linusg ✅
3 changed files with 33 additions and 1 deletions
|
@ -10,7 +10,6 @@
|
|||
#include <AK/Format.h>
|
||||
#include <AK/MemMem.h>
|
||||
#include <AK/String.h>
|
||||
#include <AK/StringBuilder.h>
|
||||
#include <AK/Utf8View.h>
|
||||
#include <AK/Vector.h>
|
||||
#include <stdlib.h>
|
||||
|
|
|
@ -14,6 +14,7 @@
|
|||
#include <AK/Optional.h>
|
||||
#include <AK/RefCounted.h>
|
||||
#include <AK/Span.h>
|
||||
#include <AK/StringBuilder.h>
|
||||
#include <AK/StringUtils.h>
|
||||
#include <AK/StringView.h>
|
||||
#include <AK/Traits.h>
|
||||
|
@ -185,6 +186,14 @@ public:
|
|||
return vformatted(fmtstr.view(), variadic_format_parameters);
|
||||
}
|
||||
|
||||
template<class SeparatorType, class CollectionType>
|
||||
static ErrorOr<String> join(SeparatorType const& separator, CollectionType const& collection, StringView fmtstr = "{}"sv)
|
||||
{
|
||||
StringBuilder builder;
|
||||
TRY(builder.try_join(separator, collection, fmtstr));
|
||||
return builder.to_string();
|
||||
}
|
||||
|
||||
// NOTE: This is primarily interesting to unit tests.
|
||||
[[nodiscard]] bool is_short_string() const;
|
||||
|
||||
|
|
|
@ -471,3 +471,27 @@ TEST_CASE(repeated)
|
|||
return Test::Crash::Failure::DidNotCrash;
|
||||
});
|
||||
}
|
||||
|
||||
TEST_CASE(join)
|
||||
{
|
||||
auto string1 = MUST(String::join(',', Vector<i32> {}));
|
||||
EXPECT(string1.is_empty());
|
||||
|
||||
auto string2 = MUST(String::join(',', Array { 1 }));
|
||||
EXPECT_EQ(string2, "1"sv);
|
||||
|
||||
auto string3 = MUST(String::join(':', Array { 1 }, "[{}]"sv));
|
||||
EXPECT_EQ(string3, "[1]"sv);
|
||||
|
||||
auto string4 = MUST(String::join(',', Array { 1, 2, 3 }));
|
||||
EXPECT_EQ(string4, "1,2,3"sv);
|
||||
|
||||
auto string5 = MUST(String::join(',', Array { 1, 2, 3 }, "[{}]"sv));
|
||||
EXPECT_EQ(string5, "[1],[2],[3]"sv);
|
||||
|
||||
auto string6 = MUST(String::join(String::from_utf8_short_string("!!!"sv), Array { "foo"sv, "bar"sv, "baz"sv }));
|
||||
EXPECT_EQ(string6, "foo!!!bar!!!baz"sv);
|
||||
|
||||
auto string7 = MUST(String::join(" - "sv, Array { 1, 16, 256, 4096 }, "[{:#04x}]"sv));
|
||||
EXPECT_EQ(string7, "[0x0001] - [0x0010] - [0x0100] - [0x1000]"sv);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue