@blinkk/editor
Version:
Structured content editor with live previews.
103 lines • 3.75 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DeepClean = void 0;
const dataType_1 = require("@blinkk/selective-edit/dist/src/utility/dataType");
class DeepClean {
constructor(config) {
this.config = config;
// Convert non-regex protected into regex.
const patterns = this.config.protectedKeyPatterns || [];
for (let i = 0; i < patterns.length; i++) {
if (dataType_1.DataType.isString(patterns[i])) {
patterns[i] = new RegExp(patterns[i]);
}
}
}
clean(value) {
if (dataType_1.DataType.isArray(value)) {
return this.cleanArray(value);
}
return this.cleanRecord(value);
}
cleanArray(originalValue) {
const newValue = [];
for (let value of originalValue) {
if (dataType_1.DataType.isObject(value)) {
// Clean in depth before testing for cleaning.
value = this.cleanRecord(value);
if (this.config.removeEmptyObjects && !Object.keys(value).length) {
continue;
}
}
else if (dataType_1.DataType.isArray(value)) {
value = this.cleanArray(value);
if (this.config.removeEmptyArrays && !value.length) {
continue;
}
}
else if (dataType_1.DataType.isString(value)) {
if (this.config.removeEmptyStrings && !value.trim().length) {
continue;
}
}
else if (dataType_1.DataType.isNull(value) && this.config.removeNulls) {
continue;
}
else if (dataType_1.DataType.isUndefined(value) && this.config.removeUndefineds) {
continue;
}
newValue.push(value);
}
return newValue;
}
cleanRecord(originalValue) {
const newValue = {};
const removeKeys = this.config.removeKeys || [];
// eslint-disable-next-line prefer-const
for (let [key, value] of Object.entries(originalValue)) {
if (this.isProtectedKey(key)) {
newValue[key] = value;
continue;
}
if (removeKeys.includes(key)) {
continue;
}
if (dataType_1.DataType.isObject(value)) {
// Clean in depth before testing for cleaning.
value = this.cleanRecord(value);
if (this.config.removeEmptyObjects && !Object.keys(value).length) {
continue;
}
}
else if (dataType_1.DataType.isArray(value)) {
value = this.cleanArray(value);
if (this.config.removeEmptyArrays && !value.length) {
continue;
}
}
else if (dataType_1.DataType.isString(value)) {
if (this.config.removeEmptyStrings && !value.trim().length) {
continue;
}
}
else if (dataType_1.DataType.isNull(value) && this.config.removeNulls) {
continue;
}
else if (dataType_1.DataType.isUndefined(value) && this.config.removeUndefineds) {
continue;
}
newValue[key] = value;
}
return newValue;
}
isProtectedKey(key) {
for (const pattern of this.config.protectedKeyPatterns || []) {
if (pattern.test(key)) {
return true;
}
}
return false;
}
}
exports.DeepClean = DeepClean;
//# sourceMappingURL=deepClean.js.map