UNPKG

@churchapps/apihelper

Version:

Library of helper functions not specific to any one ChurchApps project or framework.

118 lines 3.98 kB
// Based on https://www.npmjs.com/package/omit-empty // The project appears to be abandoned, but needed modification to allow for empty arrays. "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.OmitEmpty = void 0; class OmitEmpty { static omitEmpty(obj, options = {}) { const runtimeOpts = OmitEmpty._buildRuntimeOpts(options); const omit = (value, opts) => { if (Array.isArray(value)) { value = value.map(v => omit(v, opts)).filter(v => !OmitEmpty.isEmpty(v, opts)); } if (OmitEmpty.getType(value) === "object" && value !== null) { const result = {}; for (const key of Object.keys(value)) { if (!opts.excludedProperties.includes(key)) { const val = omit(value[key], opts); if (val !== void 0) { result[key] = val; } } } value = result; } if (!OmitEmpty.isEmpty(value, opts)) { return value; } }; const res = omit(obj, runtimeOpts); if (res === void 0) { return OmitEmpty.getType(obj) === "object" ? {} : res; } return res; } static _buildRuntimeOpts(options = {}) { return { omitZero: options.omitZero || false, omitEmptyArray: options.omitEmptyArray || false, excludedProperties: options.excludedProperties || [] }; } ; static getType(value) { if (value === null) return "null"; if (value === undefined) return "undefined"; if (Array.isArray(value)) return "array"; if (value instanceof Date) return "date"; if (value instanceof RegExp) return "regexp"; if (value instanceof Error) return "error"; if (value instanceof Map) return "map"; if (value instanceof Set) return "set"; if (value instanceof File) return "file"; const type = typeof value; if (type === "object") { // Check if it's an arguments object if (Object.prototype.toString.call(value) === '[object Arguments]') { return "arguments"; } } return type; } static isEmpty(value, runtimeOpts) { switch (OmitEmpty.getType(value)) { case "null": case "undefined": return true; case "boolean": case "function": case "date": case "regexp": return false; case "string": case "arguments": return value.length === 0; case "file": case "map": case "set": return value.size === 0; case "number": return runtimeOpts.omitZero ? value === 0 : false; case "error": return value.message === ""; case "array": if (runtimeOpts.omitEmptyArray) { for (const ele of value) { if (!OmitEmpty.isEmpty(ele, runtimeOpts)) { return false; } } return true; } else { return false; } case "object": for (const key of Object.keys(value)) { if (!OmitEmpty.isEmpty(value[key], runtimeOpts)) { return false; } } return true; default: { return true; } } } } exports.OmitEmpty = OmitEmpty; //# sourceMappingURL=OmitEmpty.js.map