@tidyjs/tidy
Version:
Tidy up your data with JavaScript, inspired by dplyr and the tidyverse
43 lines (40 loc) • 1.71 kB
JavaScript
import { processSelectors } from './select.js';
function pivotLonger(options) {
const _pivotLonger = (items) => {
var _a;
const {namesTo, valuesTo, namesSep = "_"} = options;
const cols = (_a = options.cols) != null ? _a : [];
const colsKeys = processSelectors(items, cols);
const namesToKeys = Array.isArray(namesTo) ? namesTo : [namesTo];
const valuesToKeys = Array.isArray(valuesTo) ? valuesTo : [valuesTo];
const hasMultipleNamesTo = namesToKeys.length > 1;
const hasMultipleValuesTo = valuesToKeys.length > 1;
const longer = [];
for (const item of items) {
const remainingKeys = Object.keys(item).filter((key) => !colsKeys.includes(key));
const baseObj = {};
for (const key of remainingKeys) {
baseObj[key] = item[key];
}
const nameValueKeysWithoutValuePrefix = hasMultipleValuesTo ? Array.from(new Set(colsKeys.map((key) => key.substring(key.indexOf(namesSep) + 1)))) : colsKeys;
for (const nameValue of nameValueKeysWithoutValuePrefix) {
const entryObj = {...baseObj};
for (const valueKey of valuesToKeys) {
const itemKey = hasMultipleValuesTo ? `${valueKey}${namesSep}${nameValue}` : nameValue;
const nameValueParts = hasMultipleNamesTo ? nameValue.split(namesSep) : [nameValue];
let i = 0;
for (const nameKey of namesToKeys) {
const nameValuePart = nameValueParts[i++];
entryObj[nameKey] = nameValuePart;
entryObj[valueKey] = item[itemKey];
}
}
longer.push(entryObj);
}
}
return longer;
};
return _pivotLonger;
}
export { pivotLonger };
//# sourceMappingURL=pivotLonger.js.map