AI Hints
Home›JavaScript Tutorial›Practice Projects 2
JavaScript · Lesson 119 of 138

Practice: Inventory

A map of products.

⏱ 2 min read▶ Video at 2:23:12🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

A small shop needs to track its stock. Add items when deliveries arrive, remove them when they're sold, and see what's running low. A map, from product name to quantity, is a perfect fit.

Practice: Inventory
From the video: Practice: Inventory
  • Track a shop's stock
  • Deliveries and sales
  • What's running low?

Stock with a map

Receive adds to a product's count, starting at zero for new products. Sell refuses if there isn't enough stock. Low stock turns the map's entries into an array, filters the ones under a limit, and returns their names. Run it.

app.jsjavascript
const stock = new Map();

const receive = (item, n) => stock.set(item, (stock.get(item) ?? 0) + n);

function sell(item, n) {
  const have = stock.get(item) ?? 0;
  if (n > have) return console.log(`Only ${have} ${item} left`);
  stock.set(item, have - n);
}

const lowStock = (limit) =>
  [...stock].filter(([, n]) => n < limit).map(([item]) => item);

receive("apples", 20); receive("pears", 5); receive("apples", 10);
sell("apples", 26); sell("pears", 9);
console.log(Object.fromEntries(stock), "Low:", lowStock(5));
Output
Only 5 pears left
{ apples: 4, pears: 5 } Low: [ 'apples' ]

Why a map here

Product names are the keys, and quantities are the values. A map makes adding and looking up fast, keeps the order things arrived in, and has a size property. Object from entries turns it into a normal object, which is handy for printing, or for saving as JSON.

keyvalue
Mapname → quantity
?? 0new products start at 0
[...stock]entries as an array
fromEntriesmap to object

Summary

A map from names to quantities made the inventory simple. Spread and filter found the low stock. Next, rolling dice thousands of times.

Key takeaways
  • new Map()
  • get ?? 0
  • Filter entries
Next up: Practice: Dice Statistics — simulating chance