Practice: Inventory
A map of products.
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.

- 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.
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));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.
| key | value |
|---|---|
| Map | name → quantity |
| ?? 0 | new products start at 0 |
| [...stock] | entries as an array |
| fromEntries | map 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