@snipsonian/core
Version:
Core/base reusable javascript code snippets
87 lines (86 loc) • 2.69 kB
JavaScript
import isSet from '../../is/isSet';
import isObjectPure from '../../is/isObjectPure';
import cloneObjectDataProps from '../cloneObjectDataProps';
const DEFAULT_OBSCURE_VALUE = '***obscured***';
export function obscureObjectProps({ obj, propPathsToObscure, obscureValue = DEFAULT_OBSCURE_VALUE, }) {
if (!isObjectPure(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;
}, cloneObjectDataProps(obj));
}
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 (isObjectPure(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 (isObjectPure(parentObj)) {
parentObj[lastPathPart] = newValue;
}
}
return obj;
}
function getObjectPropByPathParts({ obj, propPathParts, }) {
if (!isObjectPure(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 isSet(getObjectPropByPathParts({
obj,
propPathParts: propPath.split('.'),
}));
}