Skip to content

Instantly share code, notes, and snippets.

@big-r81
Last active August 15, 2022 16:55
Show Gist options
  • Save big-r81/62bfc3078257b5e0ba21550fcbe694c7 to your computer and use it in GitHub Desktop.
Save big-r81/62bfc3078257b5e0ba21550fcbe694c7 to your computer and use it in GitHub Desktop.
Testing ws removal functions
-module(mtest).
-export([test/0, trim_leading_and_trailing_ws/1, trim_and_reverse/1, trim_leading_and_trailing_ws_2/1, trim_string/1]).
-include_lib("eunit/include/eunit.hrl").
test() ->
S = " \t This is my test string with leading and trailing whitespaces!!! \t\t ",
St = "This is my test string with leading and trailing whitespaces!!!",
C = 1_000_000,
T1 = profile(trim_leading_and_trailing_ws, C, S),
io:format("T1 (trim_leading_and_trailing_ws) : ~p~n", [T1]),
T2 = profile(trim_and_reverse, C, S),
io:format("T2 (trim_and_reverse) : ~p~n", [T2]),
T3 = profile(trim_leading_and_trailing_ws_2, C, S),
io:format("T3 (trim_leading_and_trailing_ws_2): ~p~n", [T3]),
T4 = profile(trim_string, C, S),
io:format("T4 (string:trim/1): ~p~n", [T4]),
?assertEqual(St, trim_leading_and_trailing_ws(S)),
?assertEqual(St, trim_and_reverse(S)),
?assertEqual(St, trim_leading_and_trailing_ws_2(S)),
?assertEqual(St, trim_string(S)),
ok.
% INTERNAL API
profile(Fun, Count, S) ->
{Time, _} = timer:tc(fun() -> lists:foreach(fun(_) -> ?MODULE:Fun(S) end, lists:seq(1, Count)) end),
Time / Count.
trim_string(S) ->
string:trim(S).
trim_leading_and_trailing_ws(S) ->
re:replace(S, "^[ \\t]*|[ \\t]*$", "", [global, {return, list}]).
trim_and_reverse(S) ->
trim_and_reverse(trim_and_reverse(S, false), false).
trim_and_reverse([S | Rest], Reversed) when S=:=$ ; S=:=$\n; S=:=$\t ->
trim_and_reverse(Rest, Reversed);
trim_and_reverse(V, false) ->
trim_and_reverse(lists:reverse(V), true);
trim_and_reverse(V, true) ->
V.
-define(IS_WHITESPACE(C),
(C =:= $\s orelse C =:= $\t orelse C =:= $\r orelse C =:= $\n)).
is_whitespace(C) ->
?IS_WHITESPACE(C).
trim_leading_and_trailing_ws_2(S) ->
trim_trailing_ws(lists:dropwhile(fun is_whitespace/1, S), [], 0).
trim_trailing_ws([C | Rest], Acc, N) when ?IS_WHITESPACE(C) ->
trim_trailing_ws(Rest, [C | Acc], 1 + N);
trim_trailing_ws([C | Rest], Acc, N) ->
trim_trailing_ws(Rest, [C | Acc], 0);
trim_trailing_ws([], Acc, N) ->
lists:reverse(lists:nthtail(N, Acc)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment