/*
Lab: Let's Shop!
(1) Create a module that encapsulates a shopping cart. It should be able to:
- add items and remove items
- see a list of items
- see the total price of all items
(2) simulate two shoppers adding items to their baskets
*/
console.clear();
var cartModule = (function() {
var itemsList = []; //list of objects
var getItemsList = function() {
return itemsList;
};
var addItem = function(name, price) {
var itemObj = {name: name, price: price};
itemsList.push(itemObj);
};
var removeItem = function(name) {
for (var i=0; i<itemsList.length; ++i) {
if (itemsList[i].name === name) {
itemsList.splice(i, 1);
};
};
};
var getTotalPrice = function() {
var total = 0;
for (var i=0; i<itemsList.length; ++i) {
total += itemsList[i].price;
};
return total;
};
}());
var myCart = cartModule();
myCart.addItem('milk',3);
console.log(myCart.getItemsList());
console.log(myCart.getTotalPrice());
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.