Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Class method won't give the right output

class CoffeeShop {  
  constructor(name, menu) {
      this.name = name;
      this.menu = menu;
      this.orders = [];
  }

  addOrder(itemName) {
    this.menu.reduce((acc, meal, i, arr) => {
      meal[itemName] ? (this.orders.push(itemName), console.log("Order Added!"), arr.splice(1)) : (console.log("This item is currently unavailable!"), arr.splice(1))
    }, [])
  }

  fulfillOrder() {
    this.orders.isEmpty ? (console.log("All orders have been fulfilled!")) : (console.log(`The ${this.orders[0]} is ready!`), this.orders.shift())
  }
}


let Shop = new CoffeeShop("Shop", [
  { item: "cinnamon roll", type: "food", price: 4.99},
  { item: "hot chocolate", type: "drink", price: 2.99},
  { item: "lemon tea", type: "drink", price: 2.50}
]);

Shop.addOrder("hot chocolate");

console.log(Shop.orders);

Shop.fulfillOrder();

console.log(Shop.orders);

The output is:

This item is currently unavailable! [] The undefined is ready! []

Why isn’t the order list changing? Why does the fullfillOrder function return the opposite of what it should return even when the condition is true?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would rather used filter – to filter out added item

class CoffeeShop {  
  constructor(name, menu) {
      this.name = name;
      this.menu = menu;
      this.orders = [];
  }

  addOrder(itemName) {
    this.menu = this.menu.filter(i => {
    if(i.item === itemName) {
        this.orders.push(itemName),
        console.log("Order Added!")
        return false;
    }
    console.log("This item is currently unavailable!")
    return true;
    })
  }

  fulfillOrder() {
    this.orders.isEmpty ? (console.log("All orders have been fulfilled!")) : (console.log(`The ${this.orders[0]} is ready!`), this.orders.shift())
  }
}


let Shop = new CoffeeShop("Shop", [
  { item: "cinnamon roll", type: "food", price: 4.99},
  { item: "hot chocolate", type: "drink", price: 2.99},
  { item: "lemon tea", type: "drink", price: 2.50}
]);

Shop.addOrder("hot chocolate");

console.log(Shop.orders);

Shop.fulfillOrder();

console.log(Shop.orders);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading