Skip to content

Instantly share code, notes, and snippets.

@zeusdeux
Last active May 4, 2018 14:25
Show Gist options
  • Save zeusdeux/b64f37f619bbcec3c3c5 to your computer and use it in GitHub Desktop.
Save zeusdeux/b64f37f619bbcec3c3c5 to your computer and use it in GitHub Desktop.
Iterable higher order functions so that they play well with comprehensions
Number.prototype[Symbol.iterator] = function* (startIdx = 0) {
const endIdx = this.valueOf()
let i = startIdx
while (i < endIdx) {
yield i++
}
}
//console.log([...8]); // [0,1,2,3,4,5,6,7]
//for (let x of 8) console.log(x); // 0 1 2 3 4 5 6 7
//[...7[Symbol.iterator](4)] // [4,5,6]
// and :: (a -> Bool) -> (b -> Bool) -> (a -> b -> Bool)
function and(f, g) {
return function(a, b){
return f(a) && f(b);
}
}
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
function* zipWith(f, a, b){
var i = 0;
while(i < a.length && i < b.length) yield f(a[i], b[i]), i++;
}
//let m = [for (x of zipWith((a, b) => a + b, [1,2,3], [4,5])) x]
//console.log(m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment