sync.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.comp = exports.val = exports.Computed = exports.Value = void 0;
  4. const fanout_1 = require("./fanout");
  5. const NO_CACHE = Symbol();
  6. class Value extends fanout_1.FanOut {
  7. constructor(value) {
  8. super();
  9. /** ----------------------------------------------------- {@link SyncStore} */
  10. this.subscribe = (cb) => this.listen(cb);
  11. this.getSnapshot = () => this.value;
  12. this.value = value;
  13. }
  14. next(value, force = false) {
  15. if (!force && this.value === value)
  16. return;
  17. this.value = value;
  18. this.emit();
  19. }
  20. }
  21. exports.Value = Value;
  22. class Computed extends fanout_1.FanOut {
  23. constructor(deps, compute) {
  24. super();
  25. this.deps = deps;
  26. this.compute = compute;
  27. this.cache = NO_CACHE;
  28. /** ----------------------------------------------------- {@link SyncStore} */
  29. this.subscribe = (cb) => this.listen(cb);
  30. this.getSnapshot = () => this._comp();
  31. const subs = (this.subs = []);
  32. const length = deps.length;
  33. for (let i = 0; i < length; i++) {
  34. const dep = deps[i];
  35. const sub = dep.listen(() => {
  36. this.cache = NO_CACHE;
  37. this.emit();
  38. });
  39. subs.push(sub);
  40. }
  41. }
  42. _comp() {
  43. const cached = this.cache;
  44. if (cached !== NO_CACHE)
  45. return cached;
  46. return (this.cache = this.compute(this.deps.map((dep) => dep.getSnapshot())));
  47. }
  48. /** ----------------------------------------------------- {@link SyncValue} */
  49. get value() {
  50. return this._comp();
  51. }
  52. /** ---------------------------------------------------- {@link Disposable} */
  53. dispose() {
  54. for (const sub of this.subs)
  55. sub();
  56. }
  57. }
  58. exports.Computed = Computed;
  59. const val = (initial) => new Value(initial);
  60. exports.val = val;
  61. const comp = (deps, compute) => new Computed(deps, compute);
  62. exports.comp = comp;