@monstermann/fn
Version:
A utility library for TypeScript.
31 lines (29 loc) • 966 B
JavaScript
import { FnError } from "../function/FnError.js";
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/findRemoveLastOrThrow.ts
/**
* `findRemoveLastOrThrow(array, predicate)`
*
* Finds the last element in `array` that satisfies the provided `predicate` function and removes it, returning a new array without the removed element, or throws an error if no element is found.
*
* ```ts
* findRemoveLastOrThrow([1, 2, 3, 4], (x) => x > 2); // [1, 2, 3]
* ```
*
* ```ts
* pipe(
* [1, 2, 3, 4],
* findRemoveLastOrThrow((x) => x > 2),
* ); // [1, 2, 3]
* ```
*/
const findRemoveLastOrThrow = dfdlT((target, predicate) => {
const idx = target.findLastIndex(predicate);
if (idx === -1) throw new FnError("Array.findRemoveLastOrThrow: Value not found.", [target, predicate]);
const result = cloneArray(target);
result.splice(idx, 1);
return result;
}, 2);
//#endregion
export { findRemoveLastOrThrow };