Reputation: 9
I'm trying to figure out is each item going through reduce as the map runs, or is the map method running completely, and then after it returns the array, the reduce method is being applied to the array from the map?
const lineItems = [
{ description: 'Eggs (Dozen)', quantity: 1, price: 3, total: 3 },
{ description: 'Cheese', quantity: 0.5, price: 5, total: 2.5 },
{ description: 'Butter', quantity: 2, price: 6, total: 12 }
];
let store = lineItems.map(item => item.quantity).reduce(sumReducer, 0);
function sumReducer(sum, val) {
return sum += val;
}
console.log(store);
Upvotes: 0
Views: 45
Reputation: 3020
All regular - non generator - functions in javascript have run-to-completion semantics. This means that when they are called, the execute until they return without interruption.
In this case the map() function executes and returns an array, then the reduce() function executes.
Upvotes: 1