JavaScript, lesson 15
You now know enough JavaScript to build real programs. This lesson has two projects that are a little larger than the earlier exercises. Neither needs anything new; the challenge is organising what you know so that the code stays readable as it grows.
For a program that processes commands or text, a reliable shape is:
{ command: "add", item: "apple", qty: 5 }. Parsing in one place means the rest of the
program never deals with raw strings.Map, with methods that enforce the
rules ("you cannot sell more than you have").Errors fit naturally into this shape. The model throws when a rule is broken; the processing loop , prints a message and carries on with the next command. One bad line should not crash the whole run.
2 exercises to try what you just read.
A long chain of if (command === "add") ... else if (command === "sell") ... gets hard to
read. Because functions are values, you can store one handler per command in an object or
Map and look it up:
Adding a command is now one new line in the table.
The second project evaluates arithmetic like 2 * (3 + 4). It is the classic place where
recursion earns its keep. First, a tokenizer turns the text into a list of tokens:
numbers, operators and parentheses. A regular expression with the g flag does this neatly:
Then a recursive descent parser reads the tokens with one function per level of precedence:
expression reads terms separated by + or -;term reads factors separated by * or /;factor reads a number, a unary minus followed by a factor, or ( expression ).Because factor calls expression for the part inside parentheses, nesting of any depth just
works, and the precedence rules (multiplication before addition) fall out of which function
calls which. Keep a position variable that points at the next unread token; each function
consumes the tokens it understands and returns a number. If you meet a token you did not
expect, throw an error.
Before submitting, test by hand: empty input, a single item, unknown commands, numbers at the limits. Thinking about edge cases is half of programming.
Build a small inventory system. Each input line is a command:
| Command | Meaning |
|---|---|
add ITEM QTY PRICE | add QTY units; set the item's unit price to PRICE |
sell ITEM QTY | remove QTY units and record the revenue (QTY times the current price) |
report | print the stock report |
Rules and messages:
error: unknown item ITEM.error: only N ITEM left and changes nothing.error: unknown command WORD.report prints one line per item that has been added, sorted by item name:
ITEM: QTY in stock, value V where V is quantity times unit price with two decimals.
Then a final line revenue: R with the total revenue from all sales so far, two decimals.Sample input:
Sample output:
Write a calculator that evaluates one arithmetic expression per input line. Expressions may
contain non-negative numbers (whole or decimal), +, -, *, /, parentheses, a unary minus
(as in -3 or -(2+1)), and spaces anywhere. The usual rules apply: * and / before +
and -, operators of the same level from left to right, and parentheses first.
For each line print the result. If the result is a whole number, print it as is (like 14);
otherwise print it with exactly two decimals (like 2.50). If the expression is malformed
(for example 2 +, (1, 3 4 or 2 $ 3) or divides by zero, print error.
Sample input:
Sample output:
for (const line of lines) {
try {
handle(parse(line));
} catch (err) {
console.log(`error: ${err.message}`);
}
}const handlers = {
add: (args) => store.add(args[0], Number(args[1])),
sell: (args) => store.sell(args[0], Number(args[1])),
};
const handler = handlers[command];
if (!handler) throw new Error(`unknown command ${command}`);
handler(args);const tokens = "12*(3+4)".match(/\d+(\.\d+)?|[-+*/()]/g);
// [ '12', '*', '(', '3', '+', '4', ')' ]add pear 10 0.50
add apple 5 0.30
sell pear 4
sell kiwi 1
sell apple 9
reporterror: unknown item kiwi
error: only 5 apple left
apple: 5 in stock, value 1.50
pear: 6 in stock, value 3.00
revenue: 2.002 * (3 + 4)
10 / 4
-(2 + 3) * 2
1 / 0
2 +14
2.50
-10
error
error