Skip to content Skip to sidebar Skip to footer

How Can I Create A Cart(dictionary Function) To Add And Remove Items In Javascript

I have created below code for item in javascript. What has been giving me issues is how to create a CART (array dictionary) which is to be a function on its own that will hold item

Solution 1:

I had a bit of time so I thought I'd tackle this.

Since the instances of item are objects it's best to just store those in an array. Arrays have a lot of useful methods that can manipulate the data to match your needs.

Let's create the cart.

// Cart is capitalised.// It is a JS best-practice to capitalise your constructor function// names to differentiate them from other functionsfunctionCart() {

  // We only need an array herethis.items = [];

  // But this is new.// Returning the object allows you to chain instance methods// together when the object has been instantiatedreturnthis;
}

Cart.prototype = {

  addItem: function (item) {

    // Push a new item object into the cart arraythis.items.push(item);
    returnthis;
  },

  removeItem: function (name) {

    // We pass in the name of an item// and use filter` to filter/return all of the items *without*// that name (thus removing the item we don't want)this.items = this.items.filter(function (item) {
      return item.name !== name;
    });
  },

  showCart: function () {

    // `showCart` simply returns the arrayreturnthis.items;
  },

  getCartTotal: function () {

    // `reduce` is another useful function and allows us// to use a function to return each item total// and add it to the accumulated totalreturnthis.items.reduce(function (total, item) {
      return total + (item.quantity * item.price);
    }, 0);
  }
}

I made amendments to the Item constructor too, basically adding in return this to the methods so you can do this:

const bag = new Item('BAG').setItemPrice(50).setQuantity(80);
const scarf = new Item('SCARF').setItemPrice(10).setQuantity(20);
const bead = new Item('BEAD').setItemPrice(1).setQuantity(120);
const candle = new Item('CANDLE').setItemPrice(20).setQuantity(5);

You can the other code changes here.

Create the new cart.

const cart = newCart();

Now we can add in the items

cart.addItem(bag).addItem(scarf).addItem(bead).addItem(candle);

Get the total:

cart.getCartTotal(); // 4420

Remove the scarf item:

cart.removeItem('SCARF');

Get the new cart total:

cart.getCartTotal(); // 4220

Show the cart:

cart.showCart();

OUTPUT

[{"name":"BAG","price":50,"quantity":80,"total":0},{"name":"BEAD","price":1,"quantity":120,"total":0},{"name":"CANDLE","price":20,"quantity":5,"total":0}]

Post a Comment for "How Can I Create A Cart(dictionary Function) To Add And Remove Items In Javascript"