Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Created May 5, 2014 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joyrexus/11539705 to your computer and use it in GitHub Desktop.
Save joyrexus/11539705 to your computer and use it in GitHub Desktop.
through2-* demo

Another quick demo of through2-map and through2-filter.

Objective

  • create a stream of monotonically increasing integers
  • filter out the even integers
  • show the differences between pairwise odd numbers in stream

Sample output

B - A = DELTA
1 - 0 = 1
5 - 1 = 4
5 - 5 = 0
7 - 5 = 2
9 - 7 = 2
11 - 9 = 2
13 - 11 = 2
13 - 13 = 0
15 - 13 = 2
17 - 15 = 2
21 - 17 = 4
###
through2-* demo
* create a stream of monotonically increasing integers
* filter out the even integers
* show the differences between pairwise odd numbers in stream
###
spigot = require "stream-spigot"
filter = require "through2-filter"
map = require "through2-map"
obj =
objectMode: true
randint = (max) -> Math.floor(Math.random() * (max + 1))
nums = (x + randint(1) for x in [0..20]) # [ 0, 1, 3, 3, 5, ... 19, 19, 21 ]
source = spigot(obj, nums)
odds = filter(obj, (x) -> x % 2) # filter out evens
deltas = map obj, (x) ->
d = x - (@prev or 0) # diff between x and prev
result = "#{x} - #{@prev or 0} = #{d}" # curr - prev = delta
@prev = x
result
console.log('B - A = DELTA')
source
.pipe(odds)
.pipe(deltas)
.on('data', (d) -> console.log d)
{
"name": "thru-demo",
"version": "0.0.1",
"description": "'through2-* demo'",
"main": "index.js",
"dependencies": {
"through2-map": "~1.2.1",
"through2-filter": "~1.3.1",
"stream-spigot": "~3.0.3",
"concat-stream": "~1.4.5"
},
"author": "J. Voigt",
"license": "BSD-2-Clause"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment