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?
CodePudding user response:
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);