@monstermann/fn
Version:
A utility library for TypeScript.
39 lines (37 loc) • 1.15 kB
JavaScript
import { FnError } from "../function/FnError.js";
import { is } from "../function/is.js";
import { resolveOffset } from "./internals/offset.js";
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/setAtOrThrow.ts
/**
* `setAtOrThrow(target, idx, value)`
*
* Sets the value at the specified `idx` in `target` to `value`. If the index is out of bounds, throws an error.
*
* ```ts
* setAtOrThrow([1, 2, 3], 1, 9); // [1, 9, 3]
* setAtOrThrow([1, 2, 3], -1, 9); // [1, 2, 9]
* setAtOrThrow([1, 2, 3], 5, 9); // throws FnError
* ```
*
* ```ts
* pipe([1, 2, 3], setAtOrThrow(1, 9)); // [1, 9, 3]
* pipe([1, 2, 3], setAtOrThrow(-1, 9)); // [1, 2, 9]
* pipe([1, 2, 3], setAtOrThrow(5, 9)); // throws FnError
* ```
*/
const setAtOrThrow = dfdlT((target, idx, value) => {
const offset = resolveOffset(target, idx);
if (offset < 0) throw new FnError("Array.setAtOrThrow: Index is out of range.", [
target,
idx,
value
]);
if (is(target[offset], value)) return target;
target = cloneArray(target);
target.splice(offset, 1, value);
return target;
}, 3);
//#endregion
export { setAtOrThrow };