Lab: Let's Shop!

by Jennifer Piccione

JavaScript

/*
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());