Spreadsheet of sum formulas with subscriptions and cycle checks
A budgeting widget shows a few totals that are built from other cells. Each total is rendered by a component that subscribes to one cell, so the sheet must tell subscribers exactly when their cell’s value changes, and must refuse edits that would make a total depend on itself.
Implement a class SumSheet.
const sheet = new SumSheet();
sheet.set(cellId, input); // store a number, a formula, or null
sheet.get(cellId); // => number, the current value
sheet.subscribe(cellId, listener); // => unsubscribe()
A1 or BC12.input is one of:
=, followed by one or more terms joined by +. A term is a cell id or a non-negative number such as 3 or 2.5. Spaces may appear anywhere and are ignored;null: clears the cell.get(cellId) returns the cell’s value. An empty cell is 0, both when read directly and when a formula refers to it.eval or new Function.A1 = A1 + 1) or through other cells, set throws an Error whose message contains the word cycle.D1 = B1 + C1 where both B1 and C1 use A1) is not a cycle.subscribe(cellId, listener) works on any cell, including an empty one, and returns an unsubscribe function. Calling unsubscribe more than once is harmless. Each subscribe call is its own subscription.set, every subscription whose cell’s value changed is called once as listener(newValue, previousValue). Within one cell, subscriptions run in the order they were added. The order across cells is not specified.get inside a listener returns new values for every cell.const sheet = new SumSheet();
sheet.set('A1', 1200); // rent
sheet.set('A2', 300); // food
sheet.set('B1', '=A1 + A2 + 50'); // total
sheet.get('B1'); // => 1550
sheet.get('Z9'); // => 0
sheet.subscribe('B1', (next, prev) => console.log(prev, '->', next));
sheet.set('A2', 350); // logs: 1550 -> 1600
sheet.set('A2', '=300 + 50'); // same value: nothing logged
sheet.set('A1', '=B1'); // throws Error('... cycle ...')
sheet.get('A1'); // => 1200 (unchanged)