Get Programming with JavaScript - Listing 8.11
Listing 8.11 - Finding the total shopping bill
var getTotalBill = function (itemCosts, itemCounts) {
var total = 0;
itemCosts.forEach(function (cost, i) {
total += cost * itemCounts[i];
});
return total;
};
var costs = [ 1.99, 4.95, 2.50, 9.87 ];
var numOfEach = [ 2, 1, 5, 2 ];
console.log("The total cost is $" + getTotalBill(costs, numOfEach));
Further Adventures
Listing 8.11 - Finding the total shopping bill - Task 1
- Add an extra item to the shopping trip.
var getTotalBill = function (itemCosts, itemCounts) {
var total = 0;
itemCosts.forEach(function (cost, i) {
total += cost * itemCounts[i];
});
return total;
};
var costs = [ 1.99, 4.95, 2.50, 9.87, 6.95 ];
var numOfEach = [ 2, 1, 5, 2, 1 ];
console.log("The total cost is $" + getTotalBill(costs, numOfEach));
You could just increase one of the elements in the numOfEach array to add an extra item.
Listing 8.11 - Finding the total shopping bill - Task 2
- Change the function so that forEach iterates over itemCounts instead of itemCosts.
var getTotalBill = function (itemCosts, itemCounts) {
var total = 0;
itemCounts.forEach(function (count, i) {
total += count * itemCosts[i];
});
return total;
};
var costs = [ 1.99, 4.95, 2.50, 9.87, 6.95 ];
var numOfEach = [ 2, 1, 5, 2, 1 ];
console.log("The total cost is $" + getTotalBill(costs, numOfEach));
Listing 8.11 - Finding the total shopping bill - Tasks 3&4
- Create a single array of objects with cost and numberBought properties.
- Update getTotalBill to accept a single array of items.
var getTotalBill = function (items) {
var total = 0;
items.forEach(function (item) {
total += item.cost * item.numberBought;
});
return total;
};
var items = [
{ cost: 1.99, numberBought: 2 },
{ cost: 4.95, numberBought: 1 },
{ cost: 2.50, numberBought: 5 },
{ cost: 9.87, numberBought: 2 }
];
console.log("The total cost is $" + getTotalBill(items));