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