@tidyjs/tidy
Version:
Tidy up your data with JavaScript, inspired by dplyr and the tidyverse
57 lines (53 loc) • 1.48 kB
JavaScript
Object.defineProperty(exports, '__esModule', { value: true });
function expand(expandKeys) {
const _expand = (items) => {
const keyMap = makeKeyMap(expandKeys);
const vectors = [];
for (const key in keyMap) {
const keyValue = keyMap[key];
let values;
if (typeof keyValue === "function") {
values = keyValue(items);
} else if (Array.isArray(keyValue)) {
values = keyValue;
} else {
values = Array.from(new Set(items.map((d) => d[key])));
}
vectors.push(values.map((value) => ({[key]: value})));
}
return makeCombinations(vectors);
};
return _expand;
}
function makeCombinations(vectors) {
function combine(accum, baseObj, remainingVectors) {
if (!remainingVectors.length && baseObj != null) {
accum.push(baseObj);
return;
}
const vector = remainingVectors[0];
const newRemainingArrays = remainingVectors.slice(1);
for (const item of vector) {
combine(accum, {...baseObj, ...item}, newRemainingArrays);
}
}
const result = [];
combine(result, null, vectors);
return result;
}
function makeKeyMap(keys) {
if (Array.isArray(keys)) {
const keyMap = {};
for (const key of keys) {
keyMap[key] = key;
}
return keyMap;
} else if (typeof keys === "object") {
return keys;
}
return {[keys]: keys};
}
exports.expand = expand;
exports.makeKeyMap = makeKeyMap;
//# sourceMappingURL=expand.js.map
;