I have this function that should take some array of objects and sum up the values of the inner objects based on some keys, and conditionally add to it some values from another object.
Is there a way to optimize this code?
function sumUpKeys(objects, totals = undefined) {
const totalsSum = totals?.reduce((totalsAcc, currentTotalsItem) => {
return {
key1:
(totalsAcc.key1 || 0) +
(this.computeVal(
currentTotalsItem.num || 0,
currentTotalsItem.gross
) || 0),
key2:
(totalsAcc.key2 || 0) +
(this.computeVal(
currentTotalsItem.num || 0,
currentTotalsItem.net
) || 0),
};
}, {});
const objectsSum = objects.reduce((objectsAcc, currentObject) => {
const itemsSum = currentObject.items.reduce((itemsAcc, currentItem) => {
return {
key1:
(this.computeVal(currentObject.num, currentItem.key1) || 0) +
(itemsAcc.key1 || 0),
key2:
(this.computeVal(currentObject.num, currentItem.key2) || 0) + (
itemsAcc.key2 || 0),
};
}, {});
objectsAcc = {
key1: (objectsAcc.key1 || 0) + (itemsSum.key1 || 0),
key2: (objectsAcc.key2 || 0) + (itemsSum.key2 || 0),
};
return objectsAcc;
}, {});
// add additional services sum to the monthly charges sum
return {
key1: (objectsSum.key1 || 0) + (totalsSum?.key1 || 0),
key2: (objectsSum.key2 || 0) + (totalsSum?.key2 || 0),
};
}
function computeVal(num, val) {
return val ? val * num : undefined;
}
const objects1 = [
{
num: 3,
items: [
{
key1: 4,
key2: 2,
},
{
key1: 10,
key2: 20,
},
],
key3: 'aa',
},
{
num: 4,
items: [
{
key1: 4,
key2: 2,
},
],
key3: 'aa',
},
];
const totals1 = [
{
num: 2,
gross: 10,
net: 5,
},
{
num: 3,
gross: 6,
net: 12,
},
];
// result with totals
const result1 = sumUpKeys(objects1, totals1);
// result without totals
const result2 = sumUpKeys(objects1);
console.log(result1);
console.log(result2);
reduce
if it's possible at all? Or have fewer lines of code. \$\endgroup\$