Skip to content

Instantly share code, notes, and snippets.

@briancavalier
Last active March 4, 2016 17:12
Show Gist options
  • Select an option

  • Save briancavalier/514f4a10f7b101890c67 to your computer and use it in GitHub Desktop.

Select an option

Save briancavalier/514f4a10f7b101890c67 to your computer and use it in GitHub Desktop.
Recipe for racing two streams

Needs a description, and a meaningful example ...

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))

// Usage:
import { periodic } from 'most'

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

// emits infinitely many bs and no as
race(a, b).observe(b => console.log(b));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment