@devgrid/common
Version:
Some useful primitives
84 lines • 2.69 kB
JavaScript
import { falsely } from "./primitives";
import { isArray, isObject, isString, isFunction } from "./predicates";
export const omit = (obj, options, omitOptions) => {
if (!isObject(obj)) {
return {};
}
let isShouldOmit;
if (isFunction(options)) {
isShouldOmit = (key, value, object) => options(key, value, object);
}
else if (isArray(options)) {
if (omitOptions?.path) {
return options.reduce((acc, path) => {
if (isString(path) && path.includes('.')) {
return omitByPath(acc, path.split('.'));
}
const optionsSet = new Set([path]);
return omit(acc, (name) => optionsSet.has(name));
}, { ...obj });
}
const optionsSet = new Set(options);
isShouldOmit = (name) => optionsSet.has(name);
}
else if (isString(options)) {
if (options.includes('.') && omitOptions?.path) {
const paths = options.split('.');
return omitByPath(obj, paths);
}
else {
isShouldOmit = (val) => val.toString() === options;
}
}
else if (options instanceof RegExp) {
isShouldOmit = (key) => options.test(key.toString());
}
else if (options === true) {
return {};
}
else if (!options) {
isShouldOmit = falsely;
}
else {
throw new Error("Invalid options type");
}
const list = [...Object.getOwnPropertyNames(obj), ...Object.getOwnPropertySymbols(obj)];
const result = {};
for (let i = 0; i < list.length; i += 1) {
const key = list[i];
if (key === undefined)
continue;
const val = obj[key];
if (!isShouldOmit(key, val, obj)) {
const descr = Object.getOwnPropertyDescriptor(obj, key);
if (descr) {
if (omitOptions?.deep && isObject(val)) {
Object.defineProperty(result, key, {
...descr,
value: omit(val, options, omitOptions)
});
}
else {
Object.defineProperty(result, key, descr);
}
}
}
}
return result;
};
function omitByPath(obj, paths) {
if (!isObject(obj))
return obj;
if (paths.length === 0)
return obj;
const [current, ...rest] = paths;
const result = { ...obj };
if (rest.length === 0) {
delete result[current];
}
else if (isObject(obj[current])) {
result[current] = omitByPath(obj[current], rest);
}
return result;
}
//# sourceMappingURL=omit.js.map