UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

31 lines (29 loc) 851 B
import { FnError } from "../function/FnError.js"; import { dfdlT } from "@monstermann/dfdl"; import { cloneArray } from "@monstermann/remmi"; //#region src/array/insertAtOrThrow.ts /** * `insertAtOrThrow(array, index, value)` * * Inserts `value` at the specified `index` in `array`, returning a new array with the inserted element, or throws an error if the index is out of bounds. * * ```ts * insertAtOrThrow([1, 2, 3], 1, 10); // [1, 10, 2, 3] * ``` * * ```ts * pipe([1, 2, 3], insertAtOrThrow(1, 10)); // [1, 10, 2, 3] * ``` */ const insertAtOrThrow = dfdlT((target, idx, value) => { if (idx < 0 || idx > target.length) throw new FnError("Array.insertAtOrThrow: Index is out of range", [ target, idx, value ]); const clone = cloneArray(target); clone.splice(idx, 0, value); return clone; }, 3); //#endregion export { insertAtOrThrow };