Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zailleh/813e34fb2f85b5c5d3f38735588e3f2f to your computer and use it in GitHub Desktop.
Save zailleh/813e34fb2f85b5c5d3f38735588e3f2f to your computer and use it in GitHub Desktop.
cashRegister with function
// sum shopping cart items js
// shopping cart object
const cartForParty = {
banana: "1.25",
handkerchief: ".99",
Tshirt: "25.01",
apple: "0.60",
nalgene: "10.34",
proteinShake: "22.36"
};
// define a function for getting the sum total of a shopping cart;
const sumShoppingCart = function ( cart ) { // cart expects an object with key/value pair for items
// extract values arram from Object:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
const cartArray = Object.values(cartForParty);
let cartArrayNumValue = 0 ; // empty variable for final sum
for (let i = 0; i < cartArray.length; i = i + 1) {
// cartArrayNum[i] = Number(cartArray[i]); // not needed for output, can put this straight into the sum.
// accumlating the array of number values
cartArrayNumValue += Number(cartArray[i]);
};
// return our sum so it can be used elsewhere
return cartArrayNumValue;
}
// call our sumShoppingCart function and give it the cartForParty to sum. Print the returned sum.
console.log( sumShoppingCart( cartForParty ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment