Track Signals with Computed Values

Write the code, see it run, pass the checks.

The problem

  • hard
  • Code
  • Pro

Write signal(value) and computed(fn). signal returns an object with get(), which returns the current value, and set(next), which changes it; setting a value that's the same as the current one (Object.is) isn't a change. computed returns an object with get(), which returns what fn returns. It works out for itself which signals and computeds fn reads: nobody passes it a list. It's lazy: fn doesn't run until the first get(), and after that it runs again only during a get() that comes after a change to something it read on its last run. Otherwise get() returns the saved result without calling fn. A computed that reads another computed counts it as changed only if that one's value actually changed (Object.is). What fn reads can differ from run to run, so a signal it didn't read last time can't make it run again. fn never sets signals.

Your code must pass

  • A signal returns its value and updates on set
  • A computed doesn't run until it's read
  • Reruns only after a dependency changes
  • Setting the same value isn't a change
  • A computed of a computed reruns only when its value changes
  • Runs each computed once per change, even in a diamond
  • Tracks only the dependencies read in the last run