Skip to main content

src/twister@util.erl

-module(twister@util).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src\\twister\\util.gleam").
-export([at/2, largest/1]).

-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.

?MODULEDOC(
    " Tiny module containing utility helper functions.\n"
    " \n"
    " ## Note\n"
    " Unless you have a specific use case and no better (already existing) way to solve it,\n"
    " you should prefer other libraries or even your own code.\n"
    " \n"
).

-file("src\\twister\\util.gleam", 34).
-spec at_loop(list(DKX), integer()) -> {ok, DKX} | {error, nil}.
at_loop(In, Index) ->
    case {Index, In} of
        {Remaining, _} when Remaining < 0 ->
            {error, nil};

        {_, []} ->
            {error, nil};

        {0, [Head | _]} ->
            {ok, Head};

        {Remaining@1, [_ | Rest]} ->
            at(Rest, Remaining@1 - 1)
    end.

-file("src\\twister\\util.gleam", 26).
?DOC(
    " Get the element at specified index in the provided `List`, using 0-indexing\n"
    " (element at index 0 is the first element)\n"
    " \n"
    " If the index given is equal to or larger than the length of the `List`, return `Error(Nil)`.\n"
    " \n"
    " If the index is less than zero, return `Error(Nil)`.\n"
    " \n"
    " Otherwise return `Ok(a)` - the element at the given index.\n"
    " \n"
    " ## Note\n"
    " This function runs in `O(n)` where `n` is the index. This is due to the fact that Gleam\n"
    " `List`s are linked-lists, not arrays, so to find a given index it's necessary to traverse\n"
    " the `List` until encountering it.\n"
).
-spec at(list(DKT), integer()) -> {ok, DKT} | {error, nil}.
at(In, Index) ->
    Len = erlang:length(In),
    case {Index < Len, Index >= 0} of
        {true, true} ->
            at_loop(In, Index);

        {_, _} ->
            {error, nil}
    end.

-file("src\\twister\\util.gleam", 57).
-spec largest_loop(list(integer()), integer()) -> integer().
largest_loop(Over, Max) ->
    case Over of
        [] ->
            Max;

        [Head | Rest] ->
            largest_loop(Rest, gleam@int:max(Head, Max))
    end.

-file("src\\twister\\util.gleam", 50).
?DOC(
    " Given a `List` of `Int`s, find the largest element.\n"
    " \n"
    " If the `List` is empty, return `None`.\n"
    " \n"
    " ## Note\n"
    " This function runs in `O(n)`, where `n` is the length of the list.\n"
).
-spec largest(list(integer())) -> gleam@option:option(integer()).
largest(Indexes) ->
    case Indexes of
        [] ->
            none;

        [First | Rest] ->
            {some, largest_loop(Rest, First)}
    end.