@bemedev/decompose
Version:
Decompose object and so more
57 lines (54 loc) • 1.71 kB
JavaScript
import { merge } from 'ts-deepmerge';
import { SEPARATOR } from './constants/strings.js';
function recomposeObjectUrl(shape, value) {
const obj = {};
if (shape.length <= 0)
return obj;
const keys = shape.split(SEPARATOR);
if (keys.length === 1) {
const key = keys.shift();
obj[key] = value;
}
else {
const key = keys.shift();
obj[key] = recomposeObjectUrl(keys.join(SEPARATOR), value);
}
return obj;
}
const _recompose = shape => {
const entries = Object.entries(shape);
if (entries.length === 0)
return {};
const arr = [];
entries.forEach(([key, value]) => {
arr.push(recomposeObjectUrl(key, value));
});
return _recompose2(merge(...arr));
};
const _recompose2 = shape => {
const mustReturn = Array.isArray(shape) || typeof shape !== 'object' || shape === null;
if (mustReturn)
return shape;
const entries = Object.entries(shape).sort(([a], [b]) => a.localeCompare(b));
const isEmpty = entries.length === 0;
if (isEmpty)
return {};
const isArray = entries.every(([key]) => key.startsWith('[') && key.endsWith(']'));
if (isArray) {
const arr = [];
entries.forEach(([key, value]) => {
const index = parseInt(key.slice(1, -1), 10);
arr[index] = _recompose2(value);
});
return arr;
}
return entries.reduce((acc, [key, value]) => {
acc[key] = _recompose2(value);
return acc;
}, {});
};
const recompose = shape => _recompose(shape);
recompose.low = _recompose;
recompose.strict = _recompose;
export { recompose, recomposeObjectUrl };
//# sourceMappingURL=recompose.js.map