@snipsonian/core
Version:
Core/base reusable javascript code snippets
91 lines (90 loc) • 2.95 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.obscureObjectProps = void 0;
const isSet_1 = require("../../is/isSet");
const isObjectPure_1 = require("../../is/isObjectPure");
const cloneObjectDataProps_1 = require("../cloneObjectDataProps");
const DEFAULT_OBSCURE_VALUE = '***obscured***';
function obscureObjectProps({ obj, propPathsToObscure, obscureValue = DEFAULT_OBSCURE_VALUE, }) {
if (!(0, isObjectPure_1.default)(obj)) {
return obj;
}
return propPathsToObscure.reduce((accumulator, propPathToObscure) => {
if (isObjectPropSetByPath({
obj: accumulator,
propPath: propPathToObscure,
})) {
if (obscureValue === false) {
removeObjectByPath({
obj: accumulator,
propPath: propPathToObscure,
});
}
else {
setObjectPropByPath({
obj: accumulator,
propPath: propPathToObscure,
newValue: obscureValue,
});
}
}
return accumulator;
}, (0, cloneObjectDataProps_1.default)(obj));
}
exports.obscureObjectProps = obscureObjectProps;
function removeObjectByPath({ obj, propPath, }) {
const pathParts = propPath.split('.');
if (pathParts.length === 1) {
delete obj[pathParts[0]];
}
else if (pathParts.length > 1) {
const lastPathPart = pathParts.pop();
const parentObj = getObjectPropByPathParts({
obj,
propPathParts: pathParts,
});
if ((0, isObjectPure_1.default)(parentObj)) {
delete parentObj[lastPathPart];
}
}
return obj;
}
function setObjectPropByPath({ obj, propPath, newValue, }) {
const pathParts = propPath.split('.');
if (pathParts.length === 1) {
obj[pathParts[0]] = newValue;
}
else if (pathParts.length > 1) {
const lastPathPart = pathParts.pop();
const parentObj = getObjectPropByPathParts({
obj,
propPathParts: pathParts,
});
if ((0, isObjectPure_1.default)(parentObj)) {
parentObj[lastPathPart] = newValue;
}
}
return obj;
}
function getObjectPropByPathParts({ obj, propPathParts, }) {
if (!(0, isObjectPure_1.default)(obj)) {
return null;
}
if (!propPathParts || propPathParts.length === 0) {
return null;
}
const [firstPathPart, ...remainingPathParts] = propPathParts;
const first = obj[firstPathPart];
return propPathParts.length === 1
? first
: getObjectPropByPathParts({
obj: first,
propPathParts: remainingPathParts,
});
}
function isObjectPropSetByPath({ obj, propPath, }) {
return (0, isSet_1.default)(getObjectPropByPathParts({
obj,
propPathParts: propPath.split('.'),
}));
}