Skip to content

Commit

Permalink
Adds option to add suffix to truncate
Browse files Browse the repository at this point in the history
  • Loading branch information
dkln committed May 2, 2024
1 parent a8dfe93 commit 4234929
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
27 changes: 21 additions & 6 deletions lib/wuunder_utils/strings.ex
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,29 @@ defmodule WuunderUtils.Strings do
iex> WuunderUtils.Strings.truncate("this is a long string", 10)
"this is..."
iex> WuunderUtils.Strings.truncate("this is a long string", 20, "... data truncated")
"th... data truncated"
iex> WuunderUtils.Strings.truncate("this is a long string", 21, "... data truncated")
"this is a long string"
iex> WuunderUtils.Strings.truncate("this is a long string", 10, "very long suffix")
"very long "
"""
@spec truncate(String.t(), integer()) :: String.t()
def truncate(value, max_length)
when is_binary(value) and is_integer(max_length) and max_length > 3 do
if String.length(value) > max_length do
String.slice(value, 0..(max_length - 4)) <> "..."
@spec truncate(String.t(), integer(), String.t()) :: String.t()
def truncate(value, max_length, suffix \\ "...")
when is_binary(value) and is_integer(max_length) and max_length > 1 and is_binary(suffix) do
if max_length >= String.length(suffix) do
suffix_length = String.length(suffix)

if String.length(value) > max_length do
String.slice(value, 0..(max_length - suffix_length - 1)) <> suffix
else
value
end
else
value
truncate(suffix, max_length, "")
end
end
end
2 changes: 1 addition & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ defmodule WuunderUtils.MixProject do
def project do
[
app: :wuunder_utils,
version: "0.2.4",
version: "0.2.5",
elixir: "~> 1.14",
organization: "wuunder",
name: "Wuunder Utils",
Expand Down

0 comments on commit 4234929

Please sign in to comment.