UNPKG

softkave-js-utils

Version:

JavaScript & Typescript utility functions, types, and classes

99 lines 3.13 kB
import { last } from 'lodash-es'; import { isObjectEmpty } from '../object/index.js'; function getValueType(value) { if (value === null) { return 'null'; } if (value === undefined) { return 'undefined'; } return typeof value; } function ensureEntries(indexed, keyList) { keyList.forEach(key => { const keyString = key.join('.'); if (!indexed[keyString]) { indexed[keyString] = { key, keyType: key.map(k => typeof k), value: [], valueType: new Set(), }; } }); } function indexKV(indexed, key, keyString, value) { if (indexed[keyString]) { indexed[keyString].value.push(value); indexed[keyString].valueType.add(getValueType(value)); } else { indexed[keyString] = { key, keyType: key.map(k => typeof k), value: [value], valueType: new Set([getValueType(value)]), }; } return indexed; } function indexPrimitive(indexed, keyList, keyStringList, value) { keyList.forEach((key, index) => { var _a; const keyString = (_a = keyStringList === null || keyStringList === void 0 ? void 0 : keyStringList[index]) !== null && _a !== void 0 ? _a : key.join('.'); indexKV(indexed, key, keyString, value); }); return indexed; } function indexArray(indexed, keyList, value, options) { const lastKey = last(keyList); if (isObjectEmpty(value)) { ensureEntries(indexed, keyList); } value.forEach((item, index) => { const indexKeyList = options.flattenNumericKeys ? keyList.concat([lastKey.concat(index)]) : [lastKey.concat(index)]; if (Array.isArray(item)) { indexed = indexArray(indexed, indexKeyList, item, options); } else if (typeof item === 'object' && item !== null) { indexed = indexJson(item, options, { parentKeyList: indexKeyList, indexed, }); } else { indexed = indexPrimitive(indexed, indexKeyList, undefined, item); } }); return indexed; } export function indexJson(json, options = {}, __internal = { parentKeyList: [], indexed: {}, }) { const { parentKeyList, indexed } = __internal; if (isObjectEmpty(json)) { ensureEntries(indexed, parentKeyList); } for (const key in json) { const currentKeyList = parentKeyList.length ? parentKeyList.map(parentKey => parentKey.concat(key)) : [[key]]; if (Array.isArray(json[key])) { indexArray(indexed, currentKeyList, json[key], options); } else if (typeof json[key] === 'object' && json[key] !== null) { indexJson(json[key], options, { parentKeyList: currentKeyList, indexed, }); } else { indexPrimitive(indexed, currentKeyList, undefined, json[key]); } } return indexed; } //# sourceMappingURL=indexJson.js.map