Skip to content
Brian Cavalier edited this page Jun 17, 2016 · 1 revision

Create a stream that pairs the previous event value with the current event value, e.g. [previous, current]

import { loop, skip } from 'most'

// pairwise :: a -> Stream a -> Stream (a, a)
// Return a stream of [previous, current] event pairs
// The first pair will be [initial, first event]
const pairwise = (initial, stream) =>
	loop(pairs, initial, stream)

// pairwise1 :: Stream a -> Stream (a, a)
// Variant of pairwise without an initial value
// The first pair will be [first event, second event]
const pairwise1 = stream =>
	skip(1, pairwise(void 0, stream))

const pairs = (prev, current) =>
	({ seed: current, value: [prev, current] })

Example

import { mousemove } from '@most/dom-event'

const coords = mouseEvent =>
	({ x: mouseEvent.clientX, y: mouseEvent.clientY })

const drawLine = (prev, current) => {
	// draw a line from prev to current coordinates
}

const position = mousemove(document).map(coords)

// Use the mouse to draw
const pairs = pairwise1(position)
	.observe([prev, current] => drawLine(prev, current))
Clone this wiki locally