Skip to curriculum
Jump to the editor

24.8. A spreadsheet with formulas and dependencies

Hard
Topics

This question is in

24. Build a small library
60–90 min

A spreadsheet is a small programming language hiding in a grid. Each cell holds a number, some text, or a formula such as =SUM(A1:A3)*2 that reads other cells. Change one cell and every formula that depends on it, directly or through other formulas, must show a new value. Two formulas that read each other must not loop forever. Building one touches parsing, recursion, graphs and caching at once.

Write createSheet() in sheet.js. It returns a sheet of cells A1 to Z999.

Signature

JAVASCRIPT
function createSheet() // returns the object below

sheet.set(cell, input)   // input: a number, a string, or "" / null / undefined to clear
sheet.get(cell)          // a number, a text string, null (empty), or an error code
sheet.getInput(cell)     // what was last set, exactly as given, or null
sheet.dependents(cell)   // array of cell names, sorted

Requirements

  1. A cell name is one letter A–Z and a row 1–999 without a leading zero, in any case (b2 is B2). Any other name passed to a method throws an Error with the message Invalid cell: <name>.
  2. set accepts a finite number, a string, null or undefined; anything else throws a TypeError with the message Input must be a number, a string or null. "", null and undefined clear the cell. An empty cell's get and getInput are null.
  3. A string that starts with = is a formula. Any other string whose text is an optional -, digits and an optional decimal part (spaces around it allowed) is that number; every other string is text.
  4. Formulas use numbers (12, 3.5), cell references, +, -, *, /, parentheses and unary minus, with the usual precedence; + - and * / group left to right. Spaces are allowed between tokens. Cell names and function names ignore case.
  5. A reference to an empty cell counts as 0, to a number as that number. A reference to text, anywhere except a SUM range, gives the error #VALUE!.
  6. SUM(…) takes one or more arguments separated by commas. An argument that is a single cell or a range A1:B3 (corners in any order) adds the numbers in those cells and skips text and empty cells. Any other argument is an expression.
  7. Division by zero gives #DIV/0!. A formula that cannot be read gives #ERROR!: a missing or extra token, an unknown function, a range outside SUM, an invalid cell name, SUM() with no argument.
  8. A formula that reads an error cell gives that error. When a formula meets several errors, the first one from left to right wins (this rule is for cells that are not #CYCLE!; see rule 9).
  9. A cell that is part of a cycle of references (a cell that reads itself, directly or through others, or through a range that contains it), or that depends on one, gives #CYCLE!. This is decided from the references alone and wins over every other error: =1/0+A1 in A1 gives #CYCLE!, not #DIV/0!. Once the cycle is broken, the cells show their values again.
  10. get always reflects the current inputs: after any set, every cell that depends on the changed one shows its new value. A formula may refer to a cell that is still empty, and updates when that cell is set.
  11. dependents(cell) lists every cell whose value depends on cell, directly or not (every cell of a SUM range counts), never cell itself, sorted by column, then by row as a number (A2, A10, B1). Replacing or clearing a formula removes its old dependencies.
  12. Two sheets never share cells.

Error codes are returned by get as strings: "#VALUE!", "#DIV/0!", "#ERROR!", "#CYCLE!".

Examples

JAVASCRIPT
const s = createSheet();
s.set("A1", 10);
s.set("A2", "32");          // text that is a number
s.set("A3", "apples");
s.set("B1", "=SUM(A1:A3) * 2");
s.get("A2");                // 32
s.get("B1");                // 84: the text in A3 is skipped
s.set("A1", 18);
s.get("B1");                // 100
s.dependents("A1");         // ["B1"]
JAVASCRIPT
s.set("C1", "=A3 + 1");     // s.get("C1") is "#VALUE!"
s.set("C2", "=1/(A1-18)");  // s.get("C2") is "#DIV/0!"
s.set("C3", "=2 +");        // s.get("C3") is "#ERROR!"
s.getInput("C3");           // "=2 +"
JAVASCRIPT
s.set("D1", "=D2 + 1");
s.set("D2", "=D1");
s.get("D1");                // "#CYCLE!"
s.set("D2", 4);
s.get("D1");                // 5

Environment

  • Plain JavaScript in a browser page; the tests call the global createSheet from sheet.js.
  • eval, new Function and any other way of running the formula as JavaScript are not allowed (the page's security policy blocks them anyway). Write the parser.
  • Functions other than SUM, string literals, comparison operators, ^, columns past Z and absolute references ($A$1) are out of scope.

Hints

  1. Split the work: turn the formula text into tokens, the tokens into a tree, and evaluate the tree. Which of those can happen once, in set?
  2. While computing one cell you compute others. What would you need to remember to notice that you have come back to a cell you are still computing?
  3. To answer dependents quickly, which direction should the links between cells point?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…