feat(string): implement string_translate (closes #4)

This commit is contained in:
Alex 2024-09-13 10:09:04 +02:00
parent 46ed11c1de
commit 46845796ff
Signed by: l-x
SSH key fingerprint: SHA256:MK3uQVPHEV0Oo2ry/dAqvVK3pAwegKAwSlyfgLd/yQM
2 changed files with 49 additions and 0 deletions

View file

@ -71,3 +71,22 @@ pub fn iterator_window(i: Iterator(a), by n: Int) -> Iterator(Iterator(a)) {
pub fn iterator_window_by_2(i: Iterator(a)) -> Iterator(#(a, a)) {
iterator.zip(i, iterator.drop(i, 1))
}
/// Creates a new `String` by applying all given replacement pairs
///
/// ## Example
///
/// ```gleam
/// string_translate("www.example.com", with: [#(".", "-"), #("com", "net")])
/// // -> "www-example-net"
/// ```
///
pub fn string_translate(
string: String,
with translations: List(#(String, String)),
) -> String {
case translations {
[] -> string
[x, ..xs] -> string_translate(string.replace(string, x.0, x.1), xs)
}
}

View file

@ -92,3 +92,33 @@ pub fn iterator_window_by_2_over_size_test() {
|> iterator.to_list
|> should.equal([])
}
pub fn string_translate_none_test() {
"ABCDE"
|> brilo.string_translate([#("X", "Y")])
|> should.equal("ABCDE")
}
pub fn string_translate_empty_test() {
""
|> brilo.string_translate([#("X", "Y")])
|> should.equal("")
}
pub fn string_translate_no_translations_test() {
"ABCDE"
|> brilo.string_translate([])
|> should.equal("ABCDE")
}
pub fn string_translate_one_test() {
"ABCDE"
|> brilo.string_translate([#("C", "X")])
|> should.equal("ABXDE")
}
pub fn string_translate_in_order_test() {
"ABCDE"
|> brilo.string_translate([#("B", ""), #("D", "A"), #("E", "B")])
|> should.equal("ACAB")
}