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