Skip to content

Commit

Permalink
feat: add Effect
Browse files Browse the repository at this point in the history
  • Loading branch information
crutchcorn committed Feb 9, 2024
1 parent f4dc9da commit b7987e8
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/store/src/effect.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {Deps, Derived} from "./derived";

export class Effect {
_derived: Derived<void>;

constructor(items: Deps, effectFn: () => void) {
this._derived = new Derived(items, () => {}, {
onUpdate() {
effectFn();
},
});
}

cleanup() {
this._derived.cleanup()
}

[Symbol.dispose]() {
this.cleanup()
}
}
1 change: 1 addition & 0 deletions packages/store/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './derived'
export * from './effect'
export * from './store'
export * from './types'
60 changes: 60 additions & 0 deletions packages/store/src/tests/effect.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { Store } from '../store'
import { Derived } from '../derived'
import { expect, vi } from 'vitest'
import {Effect} from "../effect";

describe('Effect', () => {
test('Side effect free', () => {
const count = new Store(10)

const halfCount = new Derived([count], () => {
return count.state / 2
})

const doubleCount = new Derived([count], () => {
return count.state * 2
})

const sumDoubleHalfCount = new Derived([halfCount, doubleCount], () => {
return halfCount.state + doubleCount.state
})

const fn = vi.fn();
new Effect([sumDoubleHalfCount], () => fn(sumDoubleHalfCount.state));

count.setState(() => 20)

expect(fn).toHaveBeenNthCalledWith(1, 50)

count.setState(() => 30)

expect(fn).toHaveBeenNthCalledWith(2, 75)
})

/**
* A
* / \
* B C
* / \ |
* D E F
* \ / |
* \ /
* G
*/
test('Complex diamond dep problem', () => {
const a = new Store(1)
const b = new Derived([a], () => a.state)
const c = new Derived([a], () => a.state)
const d = new Derived([b], () => b.state)
const e = new Derived([b], () => b.state)
const f = new Derived([c], () => c.state)
const g = new Derived([d, e, f], () => d.state + e.state + f.state)

const fn = vi.fn();
new Effect([g], () => fn(g.state));

a.setState(() => 2)

expect(fn).toHaveBeenNthCalledWith(1, 6)
})
})

0 comments on commit b7987e8

Please sign in to comment.