UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

29 lines (27 loc) 856 B
import { is } from "../function/is.js"; import { dfdlT } from "@monstermann/dfdl"; import { cloneArray } from "@monstermann/remmi"; //#region src/array/replaceLast.ts /** * `replaceLast(target, value, replacement)` * * Replaces the last occurrence of `value` with `replacement` in `target` array. If the value is not found or if value and replacement are the same, returns the original array unchanged. * * ```ts * replaceLast([1, 2, 3, 2], 2, 5); // [1, 2, 3, 5] * ``` * * ```ts * pipe([1, 2, 3, 2], replaceLast(2, 5)); // [1, 2, 3, 5] * ``` */ const replaceLast = dfdlT((target, value, replacement) => { if (is(value, replacement)) return target; const idx = target.lastIndexOf(value); if (idx === -1) return target; const result = cloneArray(target); result.splice(idx, 1, replacement); return result; }, 3); //#endregion export { replaceLast };