The full line of code you’re looking at is:
let inStock = order.every(item => inventory[item[0]] >= item[1]);
Here it is broken down a bit:
-
order
: an array of order items
-
item
: an order item
-
inventory[item[0]] >= item[1]
: whether an item is in stock
-
order.every(...);
: returns whether all order items are in stock
item
here is an order item. All the order items are arrays with 2 elements: (1) item name, (2) quantity ordered. (Example item: ['sunglasses', 1]
.)
inventory
is an object whose properties are inventory item names, and the values are how many of each item is in stock. (Example property: sunglasses: 1000
.)
Keeping that example item and property in mind, you could “translate” your code segment like this:
item => inventory[item[0]] >= item[1] //Original code
['sunglasses', 1] => inventory[item[0]] >= item[1] //Replaced item
['sunglasses', 1] => inventory['sunglasses'] >= 1 //Replaced item[0] and item[1]
['sunglasses', 1] => 1000 >= 1 //Replaced inventory[item[0]]
['sunglasses', 1] => true //"Translated" code
So for order item ['sunglasses', 1]
, whether it is in stock is true
(because we have 1000 sunglasses in stock and we only ordered 1).
If this is true for all the order items, then order.every(...)
will return true
, making inStock
also true
.
If it makes things clearer, you could take that entire line:
let inStock = order.every(item => inventory[item[0]] >= item[1]);
and rewrite it like this instead:
let inStock = (() => {
//Check whether all items on the order are in stock in our inventory.
for (let i = 0; i < order.length; ++i) {
//Get order item.
const item = order[i];
//Get the name of the order item.
const itemName = item[0];
//Get the quantity we have in inventory of that item.
const quantityInStock = inventory[itemName];
//Get the quantity ordered of that item.
const quantityOnOrder = item[1];
//Make sure we have enough of that item in stock.
const itemInStock = quantityInStock >= quantityOnOrder;
//If this particular item isn't in stock, stop checking and return false.
if (!itemInStock) { return false; }
//Otherwise, continue the loop and make sure the next order item is in stock.
}
//If we made it here, that means all the order items were in stock.
return true;
})();