Bruce Gust
asked on
Am I explaining this "find" function correctly?
Here's the code:
I'm using this as my academic starting point in order to understand why this works: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
...tell me if I'm explaining this correctly.
existingProduct is a variable that's either going to return the matching product id or "undefined" based on whether or not the "id" that's being evaluated matches anything in the already existing products array which is a property belonging to the "cart" object.
This:
...is akin to this:
for(products as prod) {
  if(prod.id=id)
  {
    //we've got a match
  }
  else
  {
     //undefined...
  }
}
Is that right? And if not, what am I missing?
module.exports = class Cart {
static addProduct(id) {
//fetch the previous cart
fs.readFile(p, (err, fileContent) => {
let cart = {products: [], totalPrice: 0}
if(!err) {
cart = JSON.parse(fileContent);
}
});
//analyze the cart => find existing product
[b]const existingProduct = cart.products.find(prod=>prod.id===id);[/b]
//add new product / increase quantity
}
};
I'm using this as my academic starting point in order to understand why this works: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
...tell me if I'm explaining this correctly.
existingProduct is a variable that's either going to return the matching product id or "undefined" based on whether or not the "id" that's being evaluated matches anything in the already existing products array which is a property belonging to the "cart" object.
This:
cart.products.find(prod=>prod.id===id);
...is akin to this:
for(products as prod) {
  if(prod.id=id)
  {
    //we've got a match
  }
  else
  {
     //undefined...
  }
}
Is that right? And if not, what am I missing?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
You're welcome. 😊
ASKER