Skip to content

Commit 129ac36

Browse files
authored
Merge pull request #2 from martosaur/am/optimize_common_prefix
Optimize Diff.common_prefix/2
2 parents 6c15803 + f92cbe1 commit 129ac36

File tree

1 file changed

+10
-18
lines changed

1 file changed

+10
-18
lines changed

lib/dmp/diff.ex

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -759,27 +759,19 @@ defmodule Dmp.Diff do
759759
* `rest2` - `text2` with the prefix removed.
760760
"""
761761
@spec common_prefix(String.t(), String.t()) :: {String.t(), String.t(), String.t()}
762-
def common_prefix(text1, text2) do
763-
# Cache the text lengths to prevent multiple calls.
764-
text1_length = String.length(text1)
765-
text2_length = String.length(text2)
766-
n = min(text1_length, text2_length)
762+
def common_prefix(text1, text2), do: do_common_prefix("", text1, text2)
767763

768-
if n == 0 do
769-
{"", text1, text2}
770-
else
771-
prefix =
772-
Enum.reduce_while(0..(n - 1), "", fn i, acc ->
773-
ch = String.at(text1, i)
764+
defp do_common_prefix(prefix, "", text2), do: {prefix, "", text2}
765+
defp do_common_prefix(prefix, text1, ""), do: {prefix, text1, ""}
774766

775-
if ch == String.at(text2, i) do
776-
{:cont, acc <> ch}
777-
else
778-
{:halt, acc}
779-
end
780-
end)
767+
defp do_common_prefix(prefix, text1, text2) do
768+
{t1, rem1} = String.next_grapheme(text1)
769+
{t2, rem2} = String.next_grapheme(text2)
781770

782-
{prefix, String.replace_prefix(text1, prefix, ""), String.replace_prefix(text2, prefix, "")}
771+
if t1 == t2 do
772+
do_common_prefix(prefix <> t1, rem1, rem2)
773+
else
774+
{prefix, text1, text2}
783775
end
784776
end
785777

0 commit comments

Comments
 (0)