theatre/packages/dataverse/src/derivations/iterateOver.ts

34 lines
805 B
TypeScript
Raw Normal View History

import {valueDerivation} from '../Atom'
2021-06-18 13:05:06 +02:00
import type {Pointer} from '../pointer'
import {isPointer} from '../pointer'
2021-06-18 13:05:06 +02:00
import Ticker from '../Ticker'
2022-12-01 14:20:50 +01:00
import type {Prism} from './IDerivation'
2021-06-18 13:05:06 +02:00
import {isDerivation} from './IDerivation'
export default function* iterateOver<V>(
2022-12-01 14:20:50 +01:00
pointerOrDerivation: Prism<V> | Pointer<V>,
2021-06-18 13:05:06 +02:00
): Generator<V, void, void> {
let d
if (isPointer(pointerOrDerivation)) {
2022-12-01 14:20:50 +01:00
d = valueDerivation(pointerOrDerivation) as Prism<V>
2021-06-18 13:05:06 +02:00
} else if (isDerivation(pointerOrDerivation)) {
d = pointerOrDerivation
} else {
throw new Error(`Only pointers and derivations are supported`)
}
const ticker = new Ticker()
const untap = d.onChange(ticker, (v) => {})
2021-06-18 13:05:06 +02:00
try {
while (true) {
ticker.tick()
yield d.getValue()
}
} finally {
untap()
}
}