@monstermann/fn
Version:
A utility library for TypeScript.
38 lines (36 loc) • 1.18 kB
JavaScript
import { FnError } from "../function/FnError.js";
import { is } from "../function/is.js";
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/findReplaceLastOrThrow.ts
/**
* `findReplaceLastOrThrow(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, or throws an error if no element is found.
*
* ```ts
* findReplaceLastOrThrow([1, 2, 3, 4], (x) => x > 2, 99); // [1, 2, 3, 99]
* ```
*
* ```ts
* pipe(
* [1, 2, 3, 4],
* findReplaceLastOrThrow((x) => x > 2, 99),
* ); // [1, 2, 3, 99]
* ```
*/
const findReplaceLastOrThrow = dfdlT((target, predicate, replacement) => {
const idx = target.findLastIndex(predicate);
if (idx === -1) throw new FnError("Array.findReplaceLastOrThrow: Value not found", [
target,
predicate,
replacement
]);
const prev = target[idx];
if (is(prev, replacement)) return target;
const result = cloneArray(target);
result.splice(idx, 1, replacement);
return result;
}, 3);
//#endregion
export { findReplaceLastOrThrow };