Last active
September 15, 2020 18:30
-
-
Save adworse/475ee223349e4059eecae28fa5d9a105 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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