UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

34 lines (32 loc) 972 B
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/setAtOr.ts /** * `setAtOr(target, idx, value, or)` * * Sets the value at the specified `idx` in `target` to `value`. If the index is out of bounds, returns `or`. * * ```ts * setAtOr([1, 2, 3], 1, 9, []); // [1, 9, 3] * setAtOr([1, 2, 3], -1, 9, []); // [1, 2, 9] * setAtOr([1, 2, 3], 5, 9, []); // [] * ``` * * ```ts * pipe([1, 2, 3], setAtOr(1, 9, [])); // [1, 9, 3] * pipe([1, 2, 3], setAtOr(-1, 9, [])); // [1, 2, 9] * pipe([1, 2, 3], setAtOr(5, 9, [])); // [] * ``` */ const setAtOr = dfdlT((target, idx, value, or) => { const offset = resolveOffset(target, idx); if (offset < 0) return or; if (is(target[offset], value)) return target; target = cloneArray(target); target.splice(offset, 1, value); return target; }, 4); //#endregion export { setAtOr };