@toolpad/utils
Version:
Shared utilities used by Toolpad packages.
115 lines (109 loc) • 2.86 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.insert = insert;
exports.omit = omit;
exports.remove = remove;
exports.take = take;
exports.update = update;
exports.updateArray = updateArray;
exports.updateOrCreate = updateOrCreate;
exports.without = without;
/**
* Applies changes to an object in an immutable way. The `dest` object will adopt the properties of
* the `src` object. Object identity is preserved if the operation results in a no-op.
*/
function update(dest, src) {
let result;
Object.entries(src).forEach(([key, value]) => {
if (dest[key] !== value) {
result = result || {
...dest
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
result[key] = value;
}
});
return result || dest;
}
/**
* Applies changes to an object in an immutable way. The `dest` object will adopt the properties of
* the `src` object. If `dest` is undefined, `src` will be used. Object identity is preserved if
* the operation results in a no-op.
*/
function updateOrCreate(dest, src) {
return dest ? update(dest, src) : src;
}
/**
* Inserts a value in an immutable array.
*/
function insert(array, value, index) {
return [...array.slice(0, index), value, ...array.slice(index)];
}
/**
* Updates a value in an immutable array.
*/
function updateArray(array, value, index) {
return [...array.slice(0, index), value, ...array.slice(index + 1)];
}
/**
* Removes a value in an immutable array.
*/
function remove(array, index) {
return [...array.slice(0, index), ...array.slice(index + 1)];
}
/**
* Removes a set of properties from an object in an immutable way. Object identity is preserved if
* the operation results in a no-op.
*/
function omit(obj, ...keys) {
let result;
keys.forEach(key => {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
if (!result) {
result = {
...obj
};
}
delete result[key];
}
});
return result || obj;
}
/**
* Returns an object created from `obj` with only the specified `keys`. Object identity is preserved if
* the operation results in a no-op.
*/
function take(obj, ...keys) {
const keySet = new Set(keys);
let result;
Object.keys(obj).forEach(key => {
if (!keySet.has(key)) {
if (!result) {
result = {
...obj
};
}
delete result[key];
}
});
return result || obj;
}
/**
* Returns an array without any of its items equal to `value`. Object identity is preserved if
* the operation results in a no-op.
*/
function without(array, value) {
const result = [];
let found = false;
for (let i = 0; i < array.length; i += 1) {
const elm = array[i];
if (elm === value) {
found = true;
} else {
result.push(elm);
}
}
return found ? result : array;
}
;