Necesito ayuda para fusionar estas dos funciones que realizan la misma acción de agregar todos los elementos en una lista
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; }Probé de esta manera para crear una función común pero no tuve éxito:
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;}
Podría intentar implementar una función de devolución de llamada, por ejemplo
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);