JavaScriptFundamental (ES6), part 2
Signals and computed values in JavaScript
107 A computed value that recomputes only when it has to
hardBuild the two halves of a reactive system: a signal that holds a value, and a computed that derives one. A computed must record which signals it read while it ran, cache its result, and recompute only after one of those signals actually changes. Count the recomputations and assert the count. Then prove the hard part — that a computed which stopped reading a signal on its last run is no longer disturbed by it.
Stuck? Three hints, smallest first
- 1. Keep one module-level variable naming the computation currently running. A signal read while that is set knows who to call back.
- 2. Do not recompute on change. Mark the cache stale and let the next read do the work, which is what makes a diamond recompute once instead of twice.
- 3. Record the links in both directions. Before a computation re-runs, remove it from every reader list it joined last time; only rebuilding the links from scratch can drop a dependency the new run does not read.
let running = null; // the computation currently evaluating
// Both sides of every link: readers hold nodes, and each node holds the reader
// sets it joined, so it can resign from all of them before it runs again.
function signal(value) {
const readers = new Set();
return {
get() {
if (running) { readers.add(running); running.joined.add(readers); }
return value;
},
set(next) {
if (next === value) return 0; // equal is not a change
value = next;
const notified = readers.size;
for (const node of [...readers]) node.invalidate();
return notified;
},
};
}
function computed(fn) {
let cached;
let fresh = false;
let runs = 0;
const readers = new Set();
const node = {
joined: new Set(),
invalidate() {
if (!fresh) return; // already stale: do not re-notify
fresh = false;
for (const reader of [...readers]) reader.invalidate();
},
};
return {
get runs() { return runs; },
get() {
if (running) { readers.add(running); running.joined.add(readers); }
if (!fresh) {
for (const set of node.joined) set.delete(node); // resign from last run
node.joined.clear();
const outer = running;
running = node;
try { cached = fn(); runs++; fresh = true; } finally { running = outer; }
}
return cached;
},
};
}
const quantity = signal(3);
const unitKobo = signal(250000);
const chargeVat = signal(true);
const vatRate = signal(0.075);
const subtotal = computed(() => quantity.get() * unitKobo.get());
const vat = computed(() => (chargeVat.get() ? Math.round(subtotal.get() * vatRate.get()) : 0));
const total = computed(() => subtotal.get() + vat.get());
const first = [total.get(), subtotal.runs, vat.runs, total.runs];
const cachedRead = [total.get(), total.get(), subtotal.runs, total.runs];
const notifiedByQuantity = quantity.set(5);
const afterQuantity = [total.get(), subtotal.runs, vat.runs, total.runs];
const settingSameValue = quantity.set(5);
const afterNoChange = [total.get(), subtotal.runs, total.runs];
// Turning VAT off makes vat stop reading vatRate at all.
chargeVat.set(false);
const withoutVat = [total.get(), vat.runs];
const vatRateNotifiedNobody = vatRate.set(0.05);
const afterMovingAnUnreadSignal = [total.get(), vat.runs, total.runs];
// Turning it back on re-registers the dependency it had dropped.
chargeVat.set(true);
const backOn = total.get();
const vatRateMattersAgain = vatRate.set(0.075);
const diamond = signal(2);
const doubled = computed(() => diamond.get() * 2);
const tripled = computed(() => diamond.get() * 3);
const combined = computed(() => doubled.get() + tripled.get());
const diamondFirst = [combined.get(), combined.runs];
diamond.set(4);
const diamondAfter = [combined.get(), combined.runs, doubled.runs, tripled.runs];
console.log('first read :', first);
console.log('after quantity :', afterQuantity);
console.log('vat off :', withoutVat, 'then', afterMovingAnUnreadSignal);
console.log('diamond :', diamondFirst, '->', diamondAfter);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the first read computes each node exactly once', first, [806250, 1, 1, 1]);
test('reading again three times more recomputes nothing', cachedRead, [806250, 806250, 1, 1]);
test('changing a signal notifies only its direct readers', notifiedByQuantity, 1);
test('and the next read recomputes every node that depended on it, once', afterQuantity, [1343750, 2, 2, 2]);
test('setting a signal to the value it already holds changes nothing at all', [settingSameValue, afterNoChange], [0, [1343750, 2, 2]]);
test('with VAT off the total drops and vat has run three times', withoutVat, [1250000, 3]);
test('vatRate is no longer read, so moving it notifies nobody and nothing re-runs', [vatRateNotifiedNobody, afterMovingAnUnreadSignal], [0, [1250000, 3, 3]]);
test('switching VAT back on re-registers the dropped dependency', [backOn, vatRateMattersAgain], [1312500, 1]);
test('a diamond recomputes the shared bottom once per change, not twice', [diamondFirst, diamondAfter], [[10, 1], [20, 2, 2, 2]]);
Dependency tracking needs no declaration list because reading is the declaration. One variable — running — names the computation in flight, and every signal read while it is set quietly adds that computation to its readers. Setting running in a try and restoring it in finally is what makes nesting work: total reads vat, which becomes running for the length of its own body and then hands the flag back.
The seventh assertion is the one that forces the design, and getting it wrong is the usual first mistake. Recording only the forward link — signal knows its readers — makes it impossible to drop a dependency, because nothing on the signal side ever learns that a computation stopped reading it. So each node also keeps the reader sets it joined, and resigns from all of them immediately before it re-runs. On its last run vat took the chargeVat false branch and never touched vatRate, so after resigning it never rejoined, vatRate has no readers at all, and moving it notifies nobody. That is the difference between a system that scales with what is currently read and one that scales with what was ever read.
Invalidation marks stale rather than recomputing, and that laziness buys the last assertion for free. When diamond changes it invalidates doubled and tripled, each of which invalidates combined — but the second invalidation returns immediately because fresh is already false, so combined runs once on the next read. An eager system would recompute combined after doubled updated and again after tripled, and the intermediate value would be visibly wrong. That intermediate is called a glitch, and pull-based evaluation cannot have one.