UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

33 lines (31 loc) 946 B
import { is } from "../function/is.js"; import { dfdlT } from "@monstermann/dfdl"; import { cloneArray } from "@monstermann/remmi"; //#region src/array/findReplaceLast.ts /** * `findReplaceLast(array, predicate, replacement)` * * 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. * * ```ts * findReplaceLast([1, 2, 3, 4], (x) => x > 2, 10); // [1, 2, 3, 10] * ``` * * ```ts * pipe( * [1, 2, 3, 4], * findReplaceLast((x) => x > 2, 10), * ); // [1, 2, 3, 10] * ``` */ const findReplaceLast = dfdlT((target, predicate, replacement) => { const idx = target.findLastIndex(predicate); if (idx === -1) return target; const prev = target[idx]; if (is(prev, replacement)) return target; const result = cloneArray(target); result.splice(idx, 1, replacement); return result; }, 3); //#endregion export { findReplaceLast };