Files
functional-programming-snake/js/solutions/stream.js
T

72 lines
2.3 KiB
JavaScript

// m08 stream: an event stream is a pure automaton (a Mealy machine).
// Stream<A> = { step: input => [outputs, nextStream] }
// There is no hidden state: whatever a stream "remembers" lives in the next stream it returns.
// Sources may return themselves as the next stream, since they remember nothing.
export const keyDowns = { step: (i) => [i.tag === 'KeyDown' ? [i.key] : [], keyDowns] }
export const keyUps = { step: (i) => [i.tag === 'KeyUp' ? [i.key] : [], keyUps] }
// `last` is the time of the previous Time input. Multiples of ms in (last, t] fire, ascending.
const intervalFrom = (ms, last) => ({
step: (i) => {
if (i.tag !== 'Time') return [[], intervalFrom(ms, last)]
const first = Math.floor(last / ms) + 1
const count = Math.max(0, Math.floor(i.t / ms) - first + 1)
return [Array.from({ length: count }, (_, n) => (first + n) * ms), intervalFrom(ms, i.t)]
},
})
export const interval = (ms) => intervalFrom(ms, 0)
// Each combinator steps its inputs and wraps the *next* streams in the same combinator.
export const map = (s, f) => ({
step: (i) => {
const [out, next] = s.step(i)
return [out.map(f), map(next, f)]
},
})
export const filter = (s, p) => ({
step: (i) => {
const [out, next] = s.step(i)
return [out.filter(p), filter(next, p)]
},
})
export const filterMap = (s, f) => filter(map(s, f), (b) => b !== null)
export const merge = (a, b) => ({
step: (i) => {
const [outA, nextA] = a.step(i)
const [outB, nextB] = b.step(i)
return [[...outA, ...outB], merge(nextA, nextB)]
},
})
// The accumulator travels in the arguments of the next scan, not in a variable.
export const scan = (s, f, z) => ({
step: (i) => {
const [out, next] = s.step(i)
const accs = out.reduce((xs, o) => [...xs, f(xs.length === 0 ? z : xs[xs.length - 1], o)], [])
return [accs, scan(next, f, accs.length === 0 ? z : accs[accs.length - 1])]
},
})
// Only the first step is special; afterwards we are just `next`.
export const startWith = (s, v) => ({
step: (i) => {
const [out, next] = s.step(i)
return [[v, ...out], next]
},
})
export const run = (s, inputs) =>
inputs.reduce(
([outs, stream], i) => {
const [out, next] = stream.step(i)
return [[...outs, ...out], next]
},
[[], s],
)[0]