Skip to content

Commit

Permalink
Merge pull request #7 from richcarl/string-common-fixes
Browse files Browse the repository at this point in the history
Use modern Erlang string functions in Data.String.Common
  • Loading branch information
nwolverson authored Dec 24, 2024
2 parents df3cca5 + 0d68cf3 commit d13cac8
Showing 1 changed file with 7 additions and 8 deletions.
15 changes: 7 additions & 8 deletions src/Data/String/Common.erl
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,28 @@
-export(['_localeCompare'/5, replace/3, replaceAll/3, split/2, toLower/1, toUpper/1, trim/1, joinWith/2]).

'_localeCompare'(_Lt,_Eq,_Gt,_S1,_S2) -> error("not implemented").
replace(S1,S2,S3) -> iolist_to_binary(string:replace(S3, S1, S2)).
replaceAll(S1,S2,S3) -> iolist_to_binary(string:replace(S3, S1, S2, all)).

replace(S1,S2,S3) -> unicode:characters_to_binary(string:replace(S3, S1, S2)).

replaceAll(S1,S2,S3) -> unicode:characters_to_binary(string:replace(S3, S1, S2, all)).

split(Sep,S) ->
Split = string:split(S, Sep, all),
Res = case {Sep,S} of
{<<>>,<<>>} -> []; %% string:split says [<<>>] but JS says []
{<<>>,_} ->
%% string:split does not work on empty split pattern
lists:map(fun (C) -> unicode:characters_to_binary([C], utf8) end, unicode:characters_to_list(S, utf8));

%% {_,<<>>} behaves the same in JS vs string:split
_ -> Split
_ -> string:split(S, Sep, all)
end,
array:from_list(Res).

toLower(S) -> string:lowercase(S).

toUpper(S) -> string:uppercase(S).

trim(S) -> re:replace(S, "^\\s*(.*?)\\s*$","\\1", [{return, binary}, dotall]).
trim(S) -> string:trim(S).

joinWith(S, XS) ->
XS1 = lists:map(fun unicode:characters_to_list/1, array:to_list(XS)),
Res = string:join(XS1, unicode:characters_to_list(S)),
unicode:characters_to_binary(Res).
unicode:characters_to_binary(lists:join(S, array:to_list(XS))).

0 comments on commit d13cac8

Please sign in to comment.