fatten
Version:
restructures flat objects with dot-notation-like keys into optimised nested objects
47 lines (46 loc) • 1.59 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.fatten = void 0;
function camelJoin(first, second) {
return first + second.charAt(0).toUpperCase() + second.slice(1);
}
function blowUpWith(options) {
function blowUp(acc, [key, condition]) {
const [context, ...rest] = key.split(options.separator);
if (!rest.length) {
return {
...acc,
[context]: {
...(acc[context] ?? {}),
[options.leafKey]: condition,
},
};
}
return {
...acc,
[context]: blowUp(acc[context] ?? {}, [rest.join(options.separator), condition]),
};
}
return blowUp;
}
function deflate(nested, leafKey) {
return Object.fromEntries(Object.entries(nested).map(([key, value]) => {
if (key === leafKey)
return [key, value];
const values = Object.entries(value);
if (values.length === 1) {
const [nodeKey, nodeValue] = values[0];
if (nodeKey === leafKey) {
return [key, nodeValue];
}
else {
return Object.entries(deflate({ [camelJoin(key, nodeKey)]: nodeValue }, leafKey))[0];
}
}
return [key, deflate(value, leafKey)];
}));
}
function fatten(object, { separator = '.', leafKey = '_' } = { separator: '.', leafKey: '_' }) {
return deflate(Object.entries(object).reduce(blowUpWith({ separator, leafKey }), {}), leafKey);
}
exports.fatten = fatten;