@monstermann/fn
Version:
A utility library for TypeScript.
42 lines (40 loc) • 1.17 kB
JavaScript
import { is } from "../function/is.js";
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/findReplaceLastOrElse.ts
/**
* `findReplaceLastOrElse(array, predicate, replacement, callback)`
*
* 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 the result of calling `callback` with the array if no element is found.
*
* ```ts
* findReplaceLastOrElse(
* [1, 2, 3, 4],
* (x) => x > 10,
* 99,
* (arr) => arr.length,
* ); // 4
* ```
*
* ```ts
* pipe(
* [1, 2, 3, 4],
* findReplaceLastOrElse(
* (x) => x > 10,
* 99,
* (arr) => arr.length,
* ),
* ); // 4
* ```
*/
const findReplaceLastOrElse = dfdlT((target, predicate, replacement, orElse) => {
const idx = target.findLastIndex(predicate);
if (idx === -1) return orElse(target);
const prev = target[idx];
if (is(prev, replacement)) return target;
const result = cloneArray(target);
result.splice(idx, 1, replacement);
return result;
}, 4);
//#endregion
export { findReplaceLastOrElse };