@monstermann/fn
Version:
A utility library for TypeScript.
46 lines (44 loc) • 1.24 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/findMapLastOrThrow.ts
/**
* `findMapLastOrThrow(array, predicate, mapper)`
*
* Finds the last element in `array` that satisfies the provided `predicate` function and applies the `mapper` function to it, returning a new array with the mapped element, or throws an error if no element is found.
*
* ```ts
* findMapLastOrThrow(
* [1, 2, 3, 4],
* (x) => x > 2,
* (x) => x * 10,
* ); // [1, 2, 3, 40]
* ```
*
* ```ts
* pipe(
* [1, 2, 3, 4],
* findMapLastOrThrow(
* (x) => x > 2,
* (x) => x * 10,
* ),
* ); // [1, 2, 3, 40]
* ```
*/
const findMapLastOrThrow = dfdlT((target, predicate, mapper) => {
const idx = target.findLastIndex(predicate);
if (idx === -1) throw new FnError("Array.findMapLastOrThrow: Value not found.", [
target,
predicate,
mapper
]);
const prev = target[idx];
const next = mapper(prev, idx, target);
if (is(prev, next)) return target;
const result = cloneArray(target);
result.splice(idx, 1, next);
return result;
}, 3);
//#endregion
export { findMapLastOrThrow };