Skip to content

Commit

Permalink
Handle two upcase letters
Browse files Browse the repository at this point in the history
Example:
Without change:
`Recase.to_snake("SnakeACase") == "snake_acase"`

With change:
`Recase.to_snake("SnakeACase") == "snake_a_case"`
  • Loading branch information
bolek committed Feb 15, 2023
1 parent e5a8bc4 commit 3dfd00f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 8 deletions.
26 changes: 18 additions & 8 deletions lib/recase/cases/generic.ex
Original file line number Diff line number Diff line change
Expand Up @@ -107,16 +107,19 @@ defmodule Recase.Generic do
end)

Enum.each(?A..?Z, fn char ->
defp do_split(<<unquote(char), rest::binary>>, {"", acc}),
do: do_split(rest, {<<unquote(char)::utf8>>, acc})
defp do_split(<<unquote(char), _::binary>> = input, {"", acc}) do
{upcase_streak, rest} = upcase_streak(input, "")

case byte_size(upcase_streak) do
1 ->
do_split(rest, {<<unquote(char)::utf8>>, acc})

defp do_split(<<unquote(char), rest::binary>>, {curr, acc}) do
<<c::utf8, _::binary>> = String.reverse(curr)
2 ->
<<c1::utf8, c2::utf8>> = upcase_streak
do_split(rest, {<<c2::utf8>>, [c1 | acc]})

if c in ?A..?Z do
do_split(rest, {curr <> <<unquote(char)::utf8>>, acc})
else
do_split(rest, {<<unquote(char)::utf8>>, [curr | acc]})
_ ->
do_split(rest, {<<upcase_streak::binary>>, acc})
end
end
end)
Expand Down Expand Up @@ -145,4 +148,11 @@ defmodule Recase.Generic do
do_split(rest, {curr <> <<char::utf8>>, acc})
end
end

Enum.each(?A..?Z, fn char ->
defp upcase_streak(<<unquote(char), rest::binary>>, curr),
do: upcase_streak(rest, curr <> <<unquote(char)::utf8>>)
end)

defp upcase_streak(rest, upcase_streak), do: {upcase_streak, rest}
end
1 change: 1 addition & 0 deletions test/recase_test/snake_case_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ defmodule Recase.SnakeCaseTest do
assert convert("--snake-case--") == "snake_case"
assert convert("snake#case") == "snake_case"
assert convert("snake?!case") == "snake_case"
assert convert("SnakeACase") == "snake_a_case"
end

test "should return single letter" do
Expand Down

0 comments on commit 3dfd00f

Please sign in to comment.