Skip to content

Commit 4d0ccc4

Browse files
authored
Merge pull request #7 from lemorage/refine
perf(core): reduce redundant grapheme conversions in common_prefix/suffix
2 parents 23fc5b9 + 85ca1c6 commit 4d0ccc4

1 file changed

Lines changed: 17 additions & 15 deletions

File tree

src/str/core.gleam

Lines changed: 17 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -926,7 +926,8 @@ pub fn common_prefix(strings: List(String)) -> String {
926926
[single] -> single
927927
[first, ..rest] -> {
928928
let first_chars = string.to_graphemes(first)
929-
find_common_prefix(first_chars, rest, [])
929+
let others_chars = list.map(rest, string.to_graphemes)
930+
find_common_prefix(first_chars, others_chars, [])
930931
|> list.reverse
931932
|> string.concat
932933
}
@@ -935,15 +936,15 @@ pub fn common_prefix(strings: List(String)) -> String {
935936

936937
fn find_common_prefix(
937938
reference: List(String),
938-
others: List(String),
939+
others: List(List(String)),
939940
acc: List(String),
940941
) -> List(String) {
941942
case reference {
942943
[] -> acc
943944
[char, ..rest_ref] -> {
944945
let all_have_char =
945-
list.all(others, fn(s) {
946-
case string.to_graphemes(s) {
946+
list.all(others, fn(graphemes) {
947+
case graphemes {
947948
[] -> False
948949
[first, ..] -> first == char
949950
}
@@ -952,9 +953,7 @@ fn find_common_prefix(
952953
False -> acc
953954
True -> {
954955
let new_others =
955-
list.map(others, fn(s) {
956-
s |> string.to_graphemes |> list.drop(1) |> string.concat
957-
})
956+
list.map(others, fn(graphemes) { list.drop(graphemes, 1) })
958957
find_common_prefix(rest_ref, new_others, [char, ..acc])
959958
}
960959
}
@@ -968,14 +967,17 @@ fn find_common_prefix(
968967
/// common_suffix(["hello", "world"]) -> ""
969968
///
970969
pub fn common_suffix(strings: List(String)) -> String {
971-
strings
972-
|> list.map(fn(s) {
973-
s |> string.to_graphemes |> list.reverse |> string.concat
974-
})
975-
|> common_prefix
976-
|> string.to_graphemes
977-
|> list.reverse
978-
|> string.concat
970+
case strings {
971+
[] -> ""
972+
[single] -> single
973+
[first, ..rest] -> {
974+
let first_chars = string.to_graphemes(first) |> list.reverse
975+
let others_chars =
976+
list.map(rest, fn(s) { string.to_graphemes(s) |> list.reverse })
977+
find_common_prefix(first_chars, others_chars, [])
978+
|> string.concat
979+
}
980+
}
979981
}
980982

981983
// ============================================================================

0 commit comments

Comments
 (0)