TypeScript: Stock with an index signature

Keep a shop's stock in an object used as a dictionary, typed with an index signature.

What to build

A program that applies stock commands and prints what is left.

Requirements

  • Keep the stock in an object typed { [item: string]: number }.
  • add ITEM K adds K; remove ITEM K removes K if there are at least K, and otherwise prints not enough ITEM and changes nothing; show ITEM prints ITEM: K (0 if never added).
  • At the end print stock: and then ITEM K for every item with more than 0, in alphabetical order, or stock: empty if there are none.

Input

Line 1: n. Then n commands.

Output

The lines from the commands, then the stock.

Constraints

1 ≤ n ≤ 100; 1 ≤ K ≤ 1000; item names are single words.

Example

Input:

5
add pens 10
add books 3
remove pens 4
remove books 5
show pens

Output:

not enough books
pens: 6
stock:
books 3
pens 6

Why it works

With an index signature, a lookup of an item that was never added has the type number but the value undefined, so ?? 0 is the safe way to read a count, and the final listing skips items that ran out.

Examples

Example 1 · Input
5
add pens 10
add books 3
remove pens 4
remove books 5
show pens
Expected output
not enough books
pens: 6
stock:
books 3
pens 6
Example 2 · Input
3
add tea 2
remove tea 2
show coffee
Expected output
coffee: 0
stock: empty

Hints

Hint 1

interface Stock { [item: string]: number } lets any item name be a key.

Hint 2

An item not yet in the stock reads as undefined: use ?? 0.

Solution

Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";

interface Stock {
  [item: string]: number;
}

const stock: Stock = {};
const n = Number(read());
for (let i = 0; i < n; i++) {
  const [command, item, amount] = read().split(" ");
  const have = stock[item] ?? 0;
  if (command === "add") {
    stock[item] = have + Number(amount);
  } else if (command === "remove") {
    if (have < Number(amount)) console.log("not enough " + item);
    else stock[item] = have - Number(amount);
  } else {
    console.log(item + ": " + have);
  }
}
const left = Object.keys(stock).filter((item) => stock[item] > 0).sort();
if (left.length === 0) {
  console.log("stock: empty");
} else {
  console.log("stock:");
  for (const item of left) console.log(item + " " + stock[item]);
}

Lesson: Object types and interfaces →