@monstermann/fn
Version:
A utility library for TypeScript.
37 lines (35 loc) • 1.02 kB
JavaScript
import { resolveOffset } from "./internals/offset.js";
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/removeAtOrElse.ts
/**
* `removeAtOrElse(target, idx, orElse)`
*
* Removes the element at index `idx` from `target` array. Supports negative indices to count from the end. If the index is out of bounds, calls the `orElse` function with the original array and returns its result.
*
* ```ts
* removeAtOrElse([1, 2, 3], 1, () => []); // [1, 3]
* removeAtOrElse([1, 2, 3], 5, (arr) => arr); // [1, 2, 3]
* ```
*
* ```ts
* pipe(
* [1, 2, 3],
* removeAtOrElse(1, () => []),
* ); // [1, 3]
*
* pipe(
* [1, 2, 3],
* removeAtOrElse(5, (arr) => arr),
* ); // [1, 2, 3]
* ```
*/
const removeAtOrElse = dfdlT((target, idx, orElse) => {
const offset = resolveOffset(target, idx);
if (offset < 0) return orElse(target);
const result = cloneArray(target);
result.splice(offset, 1);
return result;
}, 3);
//#endregion
export { removeAtOrElse };