Basic module

array_add_if_unique

procedure · 1 overloadSource

Appends item unless the array already holds an equal element.

Returns whether it was appended and its index: the new last index, or the index of the equal element that was already there. Equality is ==, or compare when given, as for array_find. Costs a linear search, so it suits small sets; keep a Table for large ones.

ExampleOpen in playground ↗
values: [..] string;
added, index := array_add_if_unique(*values, "red");
assert(added && index == 0);
added, index = array_add_if_unique(*values, "blue");
assert(added && index == 1);

added, index = array_add_if_unique(*values, "red");
assert(!added && index == 0 && values.count == 2);
array_free(values);
array_add_if_unique :: (
    array: *[..] $T,
    item: T,
    $compare: (T, T) -> bool = null
) -> (bool, s64)

Appends item unless the array already holds an equal element.

Returns whether it was appended and its index: the new last index, or the index of the equal element that was already there. Equality is ==, or compare when given, as for array_find. Costs a linear search, so it suits small sets; keep a Table for large ones.

Parameters

array: *[..] $T
item: T
$compare: (T, T) -> bool

Returns

bool
s64
ExampleOpen in playground ↗
values: [..] string;
added, index := array_add_if_unique(*values, "red");
assert(added && index == 0);
added, index = array_add_if_unique(*values, "blue");
assert(added && index == 1);

added, index = array_add_if_unique(*values, "red");
assert(!added && index == 0 && values.count == 2);
array_free(values);

See also