Learn/JavaScript/15. Final project
Lesson 15 of 15
Sign in

JavaScript, lesson 15

Final project

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.

Plan before you type

For a program that processes commands or text, a reliable shape is:

  1. Parse: turn each raw input line into a small object, such as { command: "add", item: "apple", qty: 5 }. Parsing in one place means the rest of the program never deals with raw strings.
  2. Model: keep the program's state in a class or a Map, with methods that enforce the rules ("you cannot sell more than you have").
  3. Process: loop over the parsed input and call the model's methods.
  4. Report: format the output in one function, so a change to the output format touches only one spot.

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.

Exercise 1

Shop inventory

Press Ctrl Enter or Check to test your code.

Exercise 2

Tiny calculator

Press Ctrl Enter or Check to test your code.

catches

Dispatch tables

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.

A tiny parser

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.

Check your edges

Before submitting, test by hand: empty input, a single item, unknown commands, numbers at the limits. Thinking about edge cases is half of programming.

Further reading

  • MDN: JavaScript Guide
  • MDN: Regular expressions
  • MDN: String.prototype.match
  • MDN: Using classes

Build a small inventory system. Each input line is a command:

CommandMeaning
add ITEM QTY PRICEadd QTY units; set the item's unit price to PRICE
sell ITEM QTYremove QTY units and record the revenue (QTY times the current price)
reportprint the stock report

Rules and messages:

  • Selling an item that was never added prints error: unknown item ITEM.
  • Selling more than is in stock prints error: only N ITEM left and changes nothing.
  • Any other command word prints 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
report
error: unknown item kiwi
error: only 5 apple left
apple: 5 in stock, value 1.50
pear: 6 in stock, value 3.00
revenue: 2.00
2 * (3 + 4)
10 / 4
-(2 + 3) * 2
1 / 0
2 +
14
2.50
-10
error
error