@comodinx/query-filters
Version:
@comodinx/query-filters is a module for parsing filters in string to object.
75 lines (74 loc) • 2.23 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.invert = exports.reduce = exports.each = exports.isFunction = exports.isSymbol = exports.isObject = void 0;
const objToString = Object.prototype.toString;
const hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* Check if the value is an object.
*/
const isObject = (value) => {
const type = typeof value;
return value != null && (type === "object" || type === "function");
};
exports.isObject = isObject;
/**
* Check if the value is a symbol.
*/
const isSymbol = (value) => {
return (typeof value === "symbol" ||
(typeof value === "object" && objToString.call(value) === "[object Symbol]"));
};
exports.isSymbol = isSymbol;
/**
* Check if the value is a function.
*/
const isFunction = (value) => {
return (0, exports.isObject)(value) && objToString.call(value) === "[object Function]";
};
exports.isFunction = isFunction;
/**
* For each the collection.
*/
const each = (collection, iterator) => {
if (Array.isArray(collection)) {
collection.forEach(iterator);
return;
}
Object.keys(collection).forEach((key) => iterator(collection[key], key, collection));
};
exports.each = each;
/**
* Reduce the collection to a single value.
*/
const reduce = (collection, iterator, carry) => {
if (Array.isArray(collection)) {
return collection.reduce(iterator, carry);
}
Object.keys(collection).forEach((key) => {
carry = iterator(carry, collection[key], key, collection);
});
return carry;
};
exports.reduce = reduce;
/**
* Invert the keys and values of an object.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const invert = (obj, multiValue = false) => {
const props = Object.keys(obj);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = {};
let index = -1;
while (++index < props.length) {
const key = props[index];
const value = obj[key];
if (multiValue && hasOwnProperty.call(result, value)) {
result[value].push(key);
}
else {
result[value] = [key];
}
}
return result;
};
exports.invert = invert;