@toolpad/utils
Version:
Shared utilities used by Toolpad packages.
76 lines (67 loc) • 2.49 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.asArray = asArray;
exports.equalProperties = equalProperties;
exports.filterKeys = filterKeys;
exports.filterValues = filterValues;
exports.hasOwnProperty = hasOwnProperty;
exports.mapKeys = mapKeys;
exports.mapProperties = mapProperties;
exports.mapValues = mapValues;
function asArray(maybeArray) {
return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
}
/**
* Type aware version of Object.protoype.hasOwnProperty.
* See https://fettblog.eu/typescript-hasownproperty/
*/
function hasOwnProperty(obj, prop) {
return obj.hasOwnProperty(prop);
}
/**
* Maps `obj` to a new object. The `mapper` function receives an entry array of key and value and
* is allowed to manipulate both. It can also return `null` to omit a property from the result.
*/
function mapProperties(obj, mapper) {
return Object.fromEntries(Object.entries(obj).flatMap(entry => {
const mapped = mapper(entry);
return mapped ? [mapped] : [];
}));
}
/**
* Maps an objects' property keys. The result is a new object with the mapped keys, but the same values.
*/
function mapKeys(obj, mapper) {
return mapProperties(obj, ([key, value]) => [mapper(key), value]);
}
/**
* Maps an objects' property values. The result is a new object with the same keys, but mapped values.
*/
function mapValues(obj, mapper) {
return mapProperties(obj, ([key, value]) => [key, mapper(value, key)]);
}
/**
* Filters an objects' property values. Similar to `array.filter` but for objects. The result is a new
* object with all the properties removed for which `filter` returned `false`.
*/
function filterValues(obj, filter) {
return mapProperties(obj, ([key, value]) => filter(value) ? [key, value] : null);
}
/**
* Filters an objects' property keys. Similar to `array.filter` but for objects. The result is a new
* object with all the properties removed for which `filter` returned `false`.
*/
function filterKeys(obj, filter) {
return mapProperties(obj, ([key, value]) => filter(key) ? [key, value] : null);
}
/**
* Compares the properties of two objects. Returns `true` if all properties are strictly equal, `false`
* otherwise.
* Pass a subset of properties to only compare those.
*/
function equalProperties(obj1, obj2, subset) {
const keysToCheck = new Set(subset ?? [...Object.keys(obj1), ...Object.keys(obj2)]);
return Array.from(keysToCheck).every(key => Object.is(obj1[key], obj2[key]));
}
;