Last active
August 26, 2016 02:59
-
-
Save pmuellr/90b852cac2d63f18e15773097e0340d4 to your computer and use it in GitHub Desktop.
pull-stream examples, but using generators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
// some examples from https://pull-stream.github.io/ , but using generators | |
// function that generates random numbers forever; a source | |
function * random () { | |
while (true) { | |
yield Math.random() | |
} | |
} | |
// function that takes a number n and a stream, generates n elements from that stream | |
function * take (n, stream) { | |
for (let item of stream) { | |
if (n == 0) return | |
n-- | |
yield item | |
} | |
} | |
// function that takes a stream, and logs the elements from that stream | |
function logger (stream) { | |
let i = 0 | |
for (let item of stream) { | |
i++ | |
console.log(`${i}: ${item}`) | |
} | |
} | |
// run the pipeline "manually" | |
logger( | |
curry(take)(5)( | |
random() | |
) | |
) | |
console.log('') | |
// run the pipeline via a friendly helper | |
pipe( | |
random, | |
curry(take)(5), | |
logger | |
) | |
// friendly pipe playing helper | |
function pipe () { | |
const fns = toArray(arguments) | |
let last | |
for (let fn of fns) { | |
last = fn(last) | |
} | |
} | |
// a curry function | |
function curry (fn) { | |
let origArgLen = fn.length | |
let collArgs = toArray(arguments) | |
collArgs.shift() | |
// console.log(`curry() argLen: ${origArgLen} initArgs: ${collArgs.join(' ')}`) | |
return curried() | |
function curried () { | |
const callArgs = toArray(arguments) | |
collArgs = collArgs.concat(callArgs) | |
// console.log(`curried() collArgs ${collArgs.join(' ')}`) | |
if (collArgs.length >= origArgLen) { | |
return fn.apply(null, collArgs) | |
} else { | |
return curried | |
} | |
} | |
} | |
// convert arguments object to an array | |
function toArray(args) { | |
return [].slice.call(args) | |
} | |
// curry tester | |
function add3 (a, b, c) { | |
return a + b + c | |
} | |
/* 43 | |
console.log(curry(add3)(1, 2, 40)) | |
console.log(curry(add3, 1)( 2, 40)) | |
console.log(curry(add3, 1, 2)(40)) | |
console.log(curry(add3)(1)( 2)(40)) | |
console.log(curry(add3, 1, 2, 40)) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment