@l33tc0d3/reshape
Version:
Provides useful methods for reshaping collections
72 lines (71 loc) • 1.76 kB
JavaScript
// src/array.ts
function arrayToMap(array, keyProp, valueProps) {
const getKey = typeof keyProp === "function" ? keyProp : (item) => item[keyProp];
let getValue;
if (valueProps === undefined) {
getValue = (item) => item;
} else if (typeof valueProps === "function") {
getValue = valueProps;
} else if (Array.isArray(valueProps)) {
const props = valueProps;
getValue = (item) => {
const obj = {};
for (const prop of props) {
obj[prop] = item[prop];
}
return obj;
};
} else {
getValue = (item) => item[valueProps];
}
const map = new Map;
for (const item of array) {
map.set(getKey(item), getValue(item));
}
return map;
}
function arrayToRecord(array, keyProp, valueProps) {
const getKey = typeof keyProp === "function" ? keyProp : (item) => item[keyProp];
let getValue;
if (valueProps === undefined) {
getValue = (item) => item;
} else if (typeof valueProps === "function") {
getValue = valueProps;
} else if (Array.isArray(valueProps)) {
const props = valueProps;
getValue = (item) => {
const obj = {};
for (const prop of props) {
obj[prop] = item[prop];
}
return obj;
};
} else {
getValue = (item) => item[valueProps];
}
return array.reduce((acc, item) => {
acc[getKey(item)] = getValue(item);
return acc;
}, {});
}
// src/object.ts
function objectKeys(obj) {
return Object.keys(obj);
}
function objectValues(obj) {
return Object.values(obj);
}
function objectEntries(obj) {
return Object.entries(obj);
}
function objectFromEntries(entries) {
return Object.fromEntries(entries);
}
export {
objectValues,
objectKeys,
objectFromEntries,
objectEntries,
arrayToRecord,
arrayToMap
};