SpreadsheetLoading saved progress…

Spreadsheet

Build a Spreadsheet class that stores values in named cells and evaluates simple formulas, like the grid in any spreadsheet app. A cell holds either a plain number or a formula — a string beginning with = whose operands are joined by +, where each operand is a number literal or a reference to another cell (=A1+B1+10). Reading a cell returns its computed number, resolving any references along the way. Evaluation is lazy: formulas are computed when you read a cell, not when you write one, so changing a referenced cell shows up on the next read.

Signature

class Spreadsheet {
  // value: number              — store it as-is.
  //      | string `'=...'`     — a formula: operands joined by '+', each a
  //                              number literal or a cell name (e.g. '=A1+B1+10').
  setCell(name: string, value: number | string): void;

  // Returns the COMPUTED numeric value of `name`, resolving cell references
  // recursively. A cell that was never set resolves to 0.
  getCell(name: string): number;
}

Examples

// A formula summing two cells and a literal.
const sheet = new Spreadsheet();
sheet.setCell('A1', 2);
sheet.setCell('B1', 3);
sheet.setCell('C1', '=A1+B1+10');
sheet.getCell('C1'); // → 15
// Lazy: updating a source cell changes the dependent read.
const sheet = new Spreadsheet();
sheet.setCell('A1', 1);
sheet.setCell('B1', '=A1+1');
sheet.getCell('B1'); // → 2
sheet.setCell('A1', 100);
sheet.getCell('B1'); // → 101  (recomputed, not cached)

Notes

  • A value is a number or a formula string. Numbers are stored as-is. A string starting with = is a formula; its operands are split on + and summed.
  • References resolve recursively. An operand that names another cell is looked up with the same rules, so a chain like C = A + B then D = C + 1 resolves all the way down.
  • An unset cell reads as 0. This is true whether you call getCell on it directly or reference it inside a formula. getCell('Z9') on a fresh sheet returns 0.
  • Tolerate whitespace. '= A1 + B1 ' must evaluate the same as '=A1+B1'.
  • Addition only. Operands are joined by + and nothing else. You do not need to support -, *, /, or parentheses, and you may assume references never form a cycle.
Loading editor…