Lesson 02 | Act 2: Calculation Engine

⏱ Est. reading time: 4 min Updated on 5/7/2026

Act 2: Calculation Engine (Episodes 4-5)

From a blank app.js to a complete calculation engine

Episode 4: Write Tests First, Then Code

Scene: The first line of code isn't function add(), it's a test.

  • What is TDD: Red → Green → Refactor (three-step cycle)
  • First test: expect(evaluate("2+3×4")).toBe(14)
  • Implement tokenization: Split "2+3×4" into [2, +, 3, ×, 4]
  • Implement Shunting-yard: Convert infix to postfix [2, 3, 4, ×, +]
  • Implement RPN evaluation: 2, 3×4=12, 2+12=14
  • The feeling of passing the first green light
  • Where the plan comes from: /gsd-plan-phase 1 splits into 3 Plans, verified by plan-checker
  • Where execution comes from: /gsd-execute-phase 1 runs parallel sub-agents, each with 200k independent context
  • Core concept: Testing is not an afterthought, it's a design tool

Output Files:

  • app.js — tokenization + shunting-yard + RPN evaluation
  • tests/engine/parse.test.js — Parser tests
  • tests/engine/evaluate.test.js — Evaluator tests
  • .planning/phases/01/PLAN-01.md to PLAN-03.md — 3 execution plans

Command: /gsd-plan-phase 1, /gsd-execute-phase 1 --auto


Episode 5: Handling "Edge Cases"

Scene: Basic math is done, but real users don't just calculate 2+3.

  • 0.1 + 0.2 = 0.3 (not 0.300...04) — Scaled integer precision implementation
  • 5 ÷ 0 = Error — Graceful division-by-zero handling, returning an error string instead of throwing an exception
  • What does 100 + 5% equal? — The percentage sign has two semantics (add/subtract as a ratio, multiply/divide as ÷100)
  • +/- toggle, nested parentheses, consecutive operator replacement
  • Result formatting: 12-digit precision, trim trailing zeros, avoid scientific notation for tiny decimals
  • History management: FIFO queue, max 10 entries, immutable return
  • /gsd-verify 1 Goal backtracking: Check every "must be true" statement from the Phase goals
  • Core concept: Edge cases are the main bulk of the work

Output Files:

  • app.js — Complete calculation engine (parse / evaluate / format / history)
  • tests/engine/format.test.js — Formatting tests
  • tests/engine/percent.test.js — Percentage tests
  • tests/engine/error.test.js — Error handling tests
  • .planning/phases/01/VERIFICATION.md — Verification report
  • .planning/phases/01/REVIEW.md — Code review report

Command: /gsd-execute-phase 1 (continued), /gsd-verify 1, /gsd-code-review