@ce1pers/array-helpers
Version:
Included simple array helpers.
42 lines (41 loc) • 1.28 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteItem = exports.deleteByIndex = exports.deleteById = void 0;
/**
* Delete item from array by ID.
*/
const deleteById = (array, options) => {
const { key, value } = options;
if (options.once) {
// Filtering item by id with key and value just once.
const index = array.findIndex((item) => item[key] === value);
// Soft copy for mutating.
const copy = [...array];
// Deleting index item.
copy.splice(index, 1);
return copy;
}
else {
// Filtering item by id with key and value.
return array.filter((item) => item[key] !== value);
}
};
exports.deleteById = deleteById;
/**
* Delete item from array by index.
*/
const deleteByIndex = (array, index) => array.filter((_, __index__) => __index__ !== index);
exports.deleteByIndex = deleteByIndex;
/**
* Delete item from array.
*/
const deleteItem = (array, options) => {
switch (options?.by) {
case "id":
return (0, exports.deleteById)(array, options);
case "index":
return (0, exports.deleteByIndex)(array, options.index);
}
};
exports.deleteItem = deleteItem;
exports.default = exports.deleteItem;