Skip to content

Instantly share code, notes, and snippets.

@adworse
Last active September 15, 2020 18:30
Show Gist options
  • Save adworse/475ee223349e4059eecae28fa5d9a105 to your computer and use it in GitHub Desktop.
Save adworse/475ee223349e4059eecae28fa5d9a105 to your computer and use it in GitHub Desktop.
defmodule StringTrimmer do
def trim_utf8(string, len), do: trim(string, len, &utf8_counter/1)
def trim_utf16(string, len), do: trim(string, len, &utf16_counter/1)
def trim(string, len, counter) do
string
|> String.graphemes()
|> Enum.reduce_while({0, ""}, fn grapheme, {count, acc} ->
count = count + counter.(grapheme)
if count <= len,
do: {:cont, {count, acc <> grapheme}},
else: {:halt, {count, acc}}
end)
|> elem(1)
end
defp utf8_counter(string), do: string |> String.codepoints() |> Enum.count()
defp utf16_counter(string) do
string
|> :unicode.characters_to_binary(:utf8, :utf16)
|> byte_size()
|> div(2)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment