-module(time). -compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]). -export([to_string/1, humanise/1]). -export_type([time/0]). -type time() :: {microseconds, float()} | {milliseconds, float()} | {seconds, float()} | {minutes, float()} | {hours, float()} | {days, float()} | {weeks, float()}. -spec to_string(time()) -> binary(). to_string(Time) -> {N, Suffix} = case Time of {microseconds, Us} -> {Us, <<"us"/utf8>>}; {milliseconds, Ms} -> {Ms, <<"ms"/utf8>>}; {seconds, S} -> {S, <<"s"/utf8>>}; {minutes, M} -> {M, <<"m"/utf8>>}; {hours, H} -> {H, <<"h"/utf8>>}; {days, D} -> {D, <<"d"/utf8>>}; {weeks, W} -> {W, <<"w"/utf8>>} end, util:format(N, Suffix). -spec to_us(time()) -> float(). to_us(Time) -> case Time of {microseconds, N} -> N; {milliseconds, N@1} -> N@1 * 1000.0; {seconds, N@2} -> N@2 * 1000000.0; {minutes, N@3} -> N@3 * 60000000.0; {hours, N@4} -> N@4 * 3600000000.0; {days, N@5} -> N@5 * 86400000000.0; {weeks, N@6} -> N@6 * 604800000000.0 end. -spec humanise(time()) -> time(). humanise(Time) -> Us = to_us(Time), gleam@bool:guard( Us < 1000.0, {microseconds, Us}, fun() -> gleam@bool:guard(Us < 1000000.0, {milliseconds, case 1000.0 of +0.0 -> +0.0; -0.0 -> -0.0; Gleam@denominator -> Us / Gleam@denominator end}, fun() -> gleam@bool:guard( Us < 60000000.0, {seconds, case 1000000.0 of +0.0 -> +0.0; -0.0 -> -0.0; Gleam@denominator@1 -> Us / Gleam@denominator@1 end}, fun() -> gleam@bool:guard( Us < 3600000000.0, {minutes, case 60000000.0 of +0.0 -> +0.0; -0.0 -> -0.0; Gleam@denominator@2 -> Us / Gleam@denominator@2 end}, fun() -> gleam@bool:guard( Us < 86400000000.0, {hours, case 3600000000.0 of +0.0 -> +0.0; -0.0 -> -0.0; Gleam@denominator@3 -> Us / Gleam@denominator@3 end}, fun() -> gleam@bool:guard( Us < 604800000000.0, {days, case 86400000000.0 of +0.0 -> +0.0; -0.0 -> -0.0; Gleam@denominator@4 -> Us / Gleam@denominator@4 end}, fun() -> {weeks, case 604800000000.0 of +0.0 -> +0.0; -0.0 -> -0.0; Gleam@denominator@5 -> Us / Gleam@denominator@5 end} end ) end ) end ) end ) end) end ).