Skip to content

replaceOrElse

ts
function Array.replaceOrElse<T, U>(
    target: readonly T[],
    value: NoInfer<T>,
    replacement: NoInfer<T>,
    orElse: (target: readonly NoInfer<T>[]) => U,
): readonly T[] | U

Replaces the first occurrence of value in target with replacement. If value is not found, calls orElse with the original array.

Example

ts
import { Array } from "@monstermann/array";

Array.replaceOrElse([1, 2, 3, 2], 2, 9, () => []); // [1, 9, 3, 2]
Array.replaceOrElse([1, 2, 3], 4, 9, (arr) => arr); // [1, 2, 3]
ts
import { Array } from "@monstermann/array";

pipe(
    [1, 2, 3, 2],
    Array.replaceOrElse(2, 9, () => []),
); // [1, 9, 3, 2]

pipe(
    [1, 2, 3],
    Array.replaceOrElse(4, 9, (arr) => arr),
); // [1, 2, 3]