@monstermann/fn
Version:
A utility library for TypeScript.
29 lines (27 loc) • 807 B
JavaScript
import { dfdlT } from "@monstermann/dfdl";
import { cloneArray } from "@monstermann/remmi";
//#region src/array/insertAtOrElse.ts
/**
* `insertAtOrElse(array, index, value, callback)`
*
* Inserts `value` at the specified `index` in `array`, returning a new array with the inserted element, or the result of calling `callback` with the array if the index is out of bounds.
*
* ```ts
* insertAtOrElse([1, 2, 3], 10, 99, (arr) => arr.length); // 3
* ```
*
* ```ts
* pipe(
* [1, 2, 3],
* insertAtOrElse(10, 99, (arr) => arr.length),
* ); // 3
* ```
*/
const insertAtOrElse = dfdlT((target, idx, value, orElse) => {
if (idx < 0 || idx > target.length) return orElse(target);
const clone = cloneArray(target);
clone.splice(idx, 0, value);
return clone;
}, 4);
//#endregion
export { insertAtOrElse };