142Build an Excel-like spreadsheet with editing, formulas, dependency tracking, and virtualized rendering
Problem
The heart of a spreadsheet is its calculation engine. (The virtualised grid UI is covered in #116, and the full design in #135.) Implement createSpreadsheet() returning:
set(ref, input): set a cell ("A1","b12") to a number ("42"), text ("Total") or a formula ("=SUM(A1:A3)*2"). An empty string clears it.get(ref): the computed value: a number, a string,nullfor empty, or an error string.getInput(ref): what the user typed.onChange(listener): after everyset, calllistener(changedRefs)with the refs whose value changed (sorted); returns an unsubscribe function.getWindow(top, left, rows, cols): a 2D array of computed values for a rectangle (what a virtualised grid asks for).evaluations: a counter of formula evaluations, to prove recalculation is incremental.
Formulas support numbers, cell references, + - * / with normal precedence, parentheses, unary minus, and the functions SUM, AVERAGE, MIN and MAX with ranges (A1:B3) and lists of arguments.
Rules:
- A reference to an empty cell is
0in arithmetic. In ranges, functions ignore empty and text cells. - Errors:
#DIV/0!(division by zero),#VALUE!(text used in arithmetic),#NAME?(unknown function),#ERROR!(cannot parse),#CYCLE!(circular reference). An error in an input propagates to formulas that use it. - Changing a cell recalculates only the cells that depend on it, each once, in dependency order.
Try it yourself
Write your solution, run it, then submit to check it against the tests.
Press Run or ⌘ Enter to execute your code.
Step-by-step
Tokenise the formula (numbers, references, :, names, operators, parentheses, commas) and parse it with recursive descent: expression → term (+|- term)*, term → factor (*|/ factor)*, factor → -factor | number | reference | range | NAME(args) | (expression). Store the AST with the cell, so recalculation never re-parses.
Unlock the full solution
What's inside
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Tests
Includes 2 code listings, 5 edge cases, 4 follow-up questions.
One-time payment by UPI, card or net banking. Launch price.