Skip to content

Commit

Permalink
potentially resolve #4
Browse files Browse the repository at this point in the history
  • Loading branch information
loreanvictor committed May 10, 2024
1 parent 024a3a0 commit a29e4d5
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/select.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Source } from './source'
import { SourceLike } from './types'


export function select<T>(source: SourceLike<T>) {
return new Source<T>(emit => {
const listener = (val: T) => emit(val)
source.get(listener)

return () => source.remove(listener)
})
}
9 changes: 9 additions & 0 deletions src/state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { Subject } from './subject'


export class State<T> extends Subject<T> {
constructor(initial: T) {
super()
this.set(initial)
}
}
73 changes: 73 additions & 0 deletions src/test/select.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { State } from '../state'
import { observe } from '../observe'
import { select } from '../select'


describe(select, () => {
test('without select, higher order sources are stopped after switch.', () => {
const flag = new State(false)
const a = new State('a')
const b = new State('b')

const cb = jest.fn()
const switched = $ => $(flag) ? a : b

observe($ => cb($($(switched)!)))

expect(a.stopped).toBe(false)
expect(b.stopped).toBe(false)

flag.set(true)

expect(a.stopped).toBe(false)
expect(b.stopped).toBe(true)

flag.set(false)

expect(a.stopped).toBe(true)
expect(b.stopped).toBe(true)
})

test('with select, higher order sources are not stopped after switch.', () => {
const flag = new State(false)
const a = new State('a')
const b = new State('b')

const cb = jest.fn()
const switched = $ => $(flag) ? select(a) : select(b)

observe($ => cb($($(switched)!)))

expect(a.stopped).toBe(false)
expect(b.stopped).toBe(false)

flag.set(true)

expect(a.stopped).toBe(false)
expect(b.stopped).toBe(false)

flag.set(false)

expect(a.stopped).toBe(false)
expect(b.stopped).toBe(false)
})

test('removes its subscription when stopped.', () => {
const get = jest.fn()
const remove = jest.fn()
const stop = jest.fn()
const src = select({
get,
remove,
stop,
stops: jest.fn(),
stopped: false
})

expect(get).toHaveBeenCalled()

src.stop()
expect(remove).toHaveBeenCalled()
expect(stop).not.toHaveBeenCalled()
})
})

0 comments on commit a29e4d5

Please sign in to comment.