24.8. A spreadsheet with formulas and dependencies
Topics
This question is in
24. Build a small libraryA 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
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, sortedRequirements
- A cell name is one letter
A–Zand a row1–999without a leading zero, in any case (b2isB2). Any other name passed to a method throws anErrorwith the messageInvalid cell: <name>. setaccepts a finite number, a string,nullorundefined; anything else throws aTypeErrorwith the messageInput must be a number, a string or null."",nullandundefinedclear the cell. An empty cell'sgetandgetInputarenull.- 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. - 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. - A reference to an empty cell counts as
0, to a number as that number. A reference to text, anywhere except aSUMrange, gives the error#VALUE!. SUM(…)takes one or more arguments separated by commas. An argument that is a single cell or a rangeA1:B3(corners in any order) adds the numbers in those cells and skips text and empty cells. Any other argument is an expression.- Division by zero gives
#DIV/0!. A formula that cannot be read gives#ERROR!: a missing or extra token, an unknown function, a range outsideSUM, an invalid cell name,SUM()with no argument. - 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). - 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+A1inA1gives#CYCLE!, not#DIV/0!. Once the cycle is broken, the cells show their values again. getalways reflects the current inputs: after anyset, 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.dependents(cell)lists every cell whose value depends oncell, directly or not (every cell of aSUMrange counts), nevercellitself, sorted by column, then by row as a number (A2,A10,B1). Replacing or clearing a formula removes its old dependencies.- Two sheets never share cells.
Error codes are returned by get as strings: "#VALUE!", "#DIV/0!", "#ERROR!", "#CYCLE!".
Examples
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"]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 +"s.set("D1", "=D2 + 1");
s.set("D2", "=D1");
s.get("D1"); // "#CYCLE!"
s.set("D2", 4);
s.get("D1"); // 5Environment
- Plain JavaScript in a browser page; the tests call the global
createSheetfromsheet.js. eval,new Functionand 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 pastZand absolute references ($A$1) are out of scope.
Hints
- 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? - 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?
- To answer
dependentsquickly, 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