Skip to content
Brian Cavalier edited this page Jun 17, 2016 · 2 revisions

Pick the stream that has the earliest first event

import { merge } from '../most'

// race :: Stream a -> Stream a -> Stream a
// return a stream that imitates the input stream with
// the earliest first event
const race = (s1, s2) =>
  merge(mapToSelf(s1), mapToSelf(s2)).take(1).join()

// mapToSelf :: Stream a -> Stream (Stream a)
// Return a stream which emits itself at the time of its first event
// Given a stream of events, s = [(time1, x1), (time2, x2), ...]
// return a stream like: [(time1, s)]
const mapToSelf = s => s.take(1).map(x => s.startWith(x))

Example

import { periodic } from 'most'

const a = periodic(100, 'a').delay(1)
const b = periodic(100, 'b')

// b wins the race
// emits infinitely many bs and no as
race(a, b).observe(b => console.log(b));
Clone this wiki locally