@toolpad/utils
Version:
Shared utilities used by Toolpad packages.
102 lines (97 loc) • 2.61 kB
JavaScript
/**
* 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.
*/
export 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.
*/
export function updateOrCreate(dest, src) {
return dest ? update(dest, src) : src;
}
/**
* Inserts a value in an immutable array.
*/
export function insert(array, value, index) {
return [...array.slice(0, index), value, ...array.slice(index)];
}
/**
* Updates a value in an immutable array.
*/
export function updateArray(array, value, index) {
return [...array.slice(0, index), value, ...array.slice(index + 1)];
}
/**
* Removes a value in an immutable array.
*/
export 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.
*/
export 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.
*/
export 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.
*/
export 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;
}