Keep track of a shop's stock from a series of commands.
What to build
A program in which an object holds the state, and each command changes it.
Requirements
add NAME QTY: increase the stock of NAME. Print nothing.remove NAME QTY: if there is enough, reduce the stock and print nothing. If the quantity reaches 0, remove the item completely. If there is not enough, change nothing and printnot enough NAME.list: print each item asNAME QTY, in alphabetical order, oremptyif there is nothing.
Input
Several lines, each a command.
Output
Only what the commands above print.
Constraints
There are from 1 to 100 commands. Names are lower-case letters. Each QTY is a whole number from 1 to 1000.
Example
Input:
add pen 5
add book 2
remove pen 3
list
Output:
book 2
pen 2
Why it works
The object always holds the current truth, so each command only has to look up one name. Deleting an empty item means that list needs no special check, and sorting the keys when printing keeps the stored data simple.
Examples
add pen 5 add book 2 remove pen 3 list
book 2 pen 2
list
empty
Hints
Hint 1
Keep the stock in one object: stock[name] is the quantity.
Hint 2
For remove, use (stock[name] ?? 0) so that a missing item counts as 0.
Hint 3
Object.keys(stock).sort() gives the names in alphabetical order. delete removes a key.
Solution
Show one correct solution (try it yourself first)
const stock = {};
let line = prompt();
while (line !== null) {
const [command, name, text] = line.split(" ");
const qty = Number(text);
if (command === "add") {
stock[name] = (stock[name] ?? 0) + qty;
} else if (command === "remove") {
if ((stock[name] ?? 0) < qty) {
console.log(`not enough ${name}`);
} else {
stock[name] -= qty;
if (stock[name] === 0) {
delete stock[name];
}
}
} else {
const names = Object.keys(stock).sort();
if (names.length === 0) {
console.log("empty");
}
for (const item of names) {
console.log(item, stock[item]);
}
}
line = prompt();
}