@lyra/form-builder
Version:
Lyra form builder
33 lines (25 loc) • 811 B
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = insert;
const BEFORE = exports.BEFORE = 'before';
const AFTER = exports.AFTER = 'after';
function insert(array, position, index, ...args) {
if (position !== BEFORE && position !== AFTER) {
throw new Error(`Invalid position "${position}", must be either ${BEFORE} or ${AFTER}`);
}
const items = flatten(...args);
if (array.length === 0) {
return items;
}
const len = array.length;
const idx = Math.abs((len + index) % len) % len;
const normalizedIdx = position === 'after' ? idx + 1 : idx;
const copy = array.slice();
copy.splice(normalizedIdx, 0, ...flatten(items));
return copy;
}
function flatten(...values) {
return values.reduce((prev, item) => prev.concat(item), []);
}