@churchapps/apihelper
Version:
Library of helper functions not specific to any one ChurchApps project or framework.
94 lines • 3.32 kB
JavaScript
// Based on https://www.npmjs.com/package/omit-empty
// The project appears to be abandoned, but needed modification to allow for empty arrays.
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OmitEmpty = void 0;
const kind_of_1 = __importDefault(require("kind-of"));
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 ((0, kind_of_1.default)(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 (0, kind_of_1.default)(obj) === "object" ? {} : res;
}
return res;
}
static _buildRuntimeOpts(options = {}) {
return {
omitZero: options.omitZero || false,
omitEmptyArray: options.omitEmptyArray || false,
excludedProperties: options.excludedProperties || []
};
}
;
static isEmpty(value, runtimeOpts) {
switch ((0, kind_of_1.default)(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