@monstermann/fn
Version:
A utility library for TypeScript.
30 lines (28 loc) • 902 B
JavaScript
import { FnError } from "../function/FnError.js";
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/removeLastOrThrow.ts
/**
* `removeLastOrThrow(target, value)`
*
* Removes the last occurrence of `value` from `target` array. If the value is not found, throws an error.
*
* ```ts
* removeLastOrThrow([1, 2, 3, 2], 2); // [1, 2, 3]
* removeLastOrThrow([1, 2, 3], 4); // throws FnError
* ```
*
* ```ts
* pipe([1, 2, 3, 2], removeLastOrThrow(2)); // [1, 2, 3]
* pipe([1, 2, 3], removeLastOrThrow(4)); // throws FnError
* ```
*/
const removeLastOrThrow = dfdlT((target, value) => {
const idx = target.lastIndexOf(value);
if (idx < 0) throw new FnError("Array.removeLastOrThrow: Value not found.", [target, value]);
const result = cloneArray(target);
result.splice(idx, 1);
return result;
}, 2);
//#endregion
export { removeLastOrThrow };