diff --git a/src/brilo.gleam b/src/brilo.gleam index 233265a..fc26d75 100644 --- a/src/brilo.gleam +++ b/src/brilo.gleam @@ -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) + } +} diff --git a/test/brilo_test.gleam b/test/brilo_test.gleam index ae9fb40..f1de4cb 100644 --- a/test/brilo_test.gleam +++ b/test/brilo_test.gleam @@ -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") +}