UNPKG

@bemedev/decompose

Version:
60 lines (59 loc) 2.09 kB
import { DELIMITER, LEFT_BRACKET, RIGHT_BRACKET } from "./constants/strings.js"; import { DEFAULT_DECOMPOSE_OPTIONS } from "./constants/objects.js"; import { isPrimitive } from "./helpers.js"; //#region src/decompose.ts function ddecompose(arg, prev = "", options = DEFAULT_DECOMPOSE_OPTIONS, first = true) { const { object } = { ...DEFAULT_DECOMPOSE_OPTIONS, ...options }; const canAddObjectKeys = object === "both" || object === "object"; const canAddKeys = object === "both" || object === "key"; const _prev = prev ? prev + DELIMITER : ""; const output = []; if (Array.isArray(arg)) { if (canAddObjectKeys && !first) output.push([`${prev}`, arg]); arg.forEach((item, index) => { const values = ddecompose(item, `${_prev}${LEFT_BRACKET}${index}${RIGHT_BRACKET}`, options, false); output.push(...values); }); return output; } if (isPrimitive(arg)) { const isFirst = !prev.includes(DELIMITER); if (canAddKeys || isFirst) output.push([`${prev}`, arg]); return output; } if (canAddObjectKeys && prev !== "") output.push([`${prev}`, arg]); Object.entries(arg).forEach(([key, value]) => { const values = ddecompose(value, `${_prev}${key}`, options, false); output.push(...values); }); return output; } const _decompose = (val, options) => { const entries1 = ddecompose(val, "", options); const { sep, start } = { ...DEFAULT_DECOMPOSE_OPTIONS, ...options }; if (entries1.length == 0) { if (Array.isArray(val)) return []; return {}; } const regexDel = new RegExp(DELIMITER, "g"); const regexLeft = new RegExp(LEFT_BRACKET, "g"); const regexRight = new RegExp(RIGHT_BRACKET, "g"); const entries2 = entries1.map(([__key, value]) => { const _key = __key.replace(regexDel, sep).replace(regexLeft, `[`).replace(regexRight, `]`); return [start ? `${sep}${_key}` : _key, value]; }); return Object.fromEntries(entries2); }; /* v8 ignore next 1 */ const decompose = (val, options) => _decompose(val, options); decompose.low = decompose; decompose.strict = decompose; //#endregion export { decompose }; //# sourceMappingURL=decompose.js.map