UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

33 lines (31 loc) 994 B
import { is } from "../function/is.js"; import { dfdlT } from "@monstermann/dfdl"; import { cloneArray } from "@monstermann/remmi"; //#region src/array/findReplaceLastOr.ts /** * `findReplaceLastOr(array, predicate, replacement, fallback)` * * Finds the last element in `array` that satisfies the provided `predicate` function and replaces it with `replacement`, returning a new array with the replaced element, or `fallback` if no element is found. * * ```ts * findReplaceLastOr([1, 2, 3, 4], (x) => x > 10, 99, []); // [] * ``` * * ```ts * pipe( * [1, 2, 3, 4], * findReplaceLastOr((x) => x > 10, 99, []), * ); // [] * ``` */ const findReplaceLastOr = dfdlT((target, predicate, replacement, or) => { const idx = target.findLastIndex(predicate); if (idx === -1) return or; const prev = target[idx]; if (is(prev, replacement)) return target; const result = cloneArray(target); result.splice(idx, 1, replacement); return result; }, 4); //#endregion export { findReplaceLastOr };