I need help in merging these two function that are performing the same action of adding all the elements in a list
function totalSpendings() {
let totalSpending = 0;
if (this.spendingList.length > 0) {
totalSpending = this.spendingList.reduce(function (
totalValue,
curentValue
) {
totalValue += curentValue.inputSpending;
return totalValue;
},
0);
}
this.spending_summary.textContent = totalSpending;
return totalSpending;
}
function totalEarnings() {
let totalEarning = 0;
if (this.earningList.length > 0) {
totalEarning = this.earningList.reduce(function (totalValue, curentValue) {
totalValue += curentValue.inputEarning;
return totalValue;
}, 0);
}
this.earning_summary.textContent = totalEarning;
return totalEarning;
}
I tried out this way to create a common function but was unsuccessful :
total(arg1,arg2,arg3){
let total = 0;
if (arg1.length > 0) {
total = arg1.reduce(function (totalValue, curentValue) {
totalValue += arg3;
return totalValue;
}, 0);
}
arg2.textContent = total
return total;
}
You could try to implement a callback function, e.g.
const spending_summary = {};
const earning_summary = {};
const spendingList = [
{inputSpending: 1},
{inputSpending: 2},
];
const earningList = [
{ inputEarning: 1},
{ inputEarning: 2},
];
function total(list, reducer) {
if (list && list.length > 0) {
return list.reduce(reducer, 0);
}
return 0;
}
spending_summary.textContent = total(spendingList, (total, current) => total += current.inputSpending);
earning_summary.textContent = total(earningList, (total, current) => total += current.inputEarning);
console.log(spending_summary);
console.log(earning_summary);