Build a Cart object using javascript with these three methods: chart.add('chair', 3); chart.add('chair'); //will add only 1 element chart.add('table', 2); chart.remove('table') // it will remove 1 element each time. chart.show(); // will show the elements and its quantity ordered by name // chair: 4, // table: 1
Sigiloso
function Cart() { this.cart = {}; } Cart.prototype = { add: function(element, num) { if (!this.cart[element]) { this.cart[element] = (num) ? num : 1; } else { this.cart[element] += (num) ? num : 1; } }, remove: function(element) { this.cart[element] -= 1; }, show: function() { var res = []; var keys = Object.keys(this.cart); keys.sort(); for (var i = 0; i < keys.length; i++) { console.log(keys[i] + ': ' + this.cart[keys[i]]); } } } var cart = new Cart(); cart.add('chairs', 2); cart.add('chairs'); cart.add('table', 5); cart.add('lamps', 7); cart.remove('lamps'); cart.show();