UNPKG

@devgrid/common

Version:
88 lines 2.97 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.omit = void 0; const primitives_1 = require("./primitives"); const predicates_1 = require("./predicates"); const omit = (obj, options, omitOptions) => { if (!(0, predicates_1.isObject)(obj)) { return {}; } let isShouldOmit; if ((0, predicates_1.isFunction)(options)) { isShouldOmit = (key, value, object) => options(key, value, object); } else if ((0, predicates_1.isArray)(options)) { if (omitOptions?.path) { return options.reduce((acc, path) => { if ((0, predicates_1.isString)(path) && path.includes('.')) { return omitByPath(acc, path.split('.')); } const optionsSet = new Set([path]); return (0, exports.omit)(acc, (name) => optionsSet.has(name)); }, { ...obj }); } const optionsSet = new Set(options); isShouldOmit = (name) => optionsSet.has(name); } else if ((0, predicates_1.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 = primitives_1.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 && (0, predicates_1.isObject)(val)) { Object.defineProperty(result, key, { ...descr, value: (0, exports.omit)(val, options, omitOptions) }); } else { Object.defineProperty(result, key, descr); } } } } return result; }; exports.omit = omit; function omitByPath(obj, paths) { if (!(0, predicates_1.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 ((0, predicates_1.isObject)(obj[current])) { result[current] = omitByPath(obj[current], rest); } return result; } //# sourceMappingURL=omit.js.map