This Gist was automatically created by Carbide, a free online programming environment.
Created
March 24, 2017 00:20
Star
You must be signed in to star a gist
untitled
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
const Numbers = { | |
[Symbol.iterator] () { | |
let n = 0; | |
return { | |
next: () => | |
({done: false, value: n++}) | |
} | |
} | |
} | |
const RandomNumbers = { | |
[Symbol.iterator]: () => | |
({ | |
next () { | |
return {value: Math.random()}; | |
} | |
}) | |
} | |
const mapWith = (fn, collection) => | |
({ | |
[Symbol.iterator] () { | |
const iterator = collection[Symbol.iterator](); | |
return { | |
next () { | |
const {done, value} = iterator.next(); | |
return ({done, value: done ? undefined : fn(value)}); | |
} | |
} | |
} | |
}); | |
const filterWith = (fn, iterable) => | |
({ | |
[Symbol.iterator] () { | |
const iterator = iterable[Symbol.iterator](); | |
return { | |
next () { | |
do { | |
const {done, value} = iterator.next(); | |
} while (!done && !fn(value)); | |
return {done, value}; | |
} | |
} | |
} | |
}); | |
const untilWith = (fn, iterable) => | |
({ | |
[Symbol.iterator] () { | |
const iterator = iterable[Symbol.iterator](); | |
return { | |
next () { | |
let {done, value} = iterator.next(); | |
done = done || fn(value); | |
return ({done, value: done ? undefined : value}); | |
} | |
} | |
} | |
}); | |
const gather = (iterable) => { | |
const g = []; | |
for (const i of iterable) { | |
g.push(i); | |
} | |
return g.toString(); | |
} | |
const a = [1,2,3,4,5,6,7,8,9,10]; | |
const Evens = mapWith(x => x * 2, a); | |
const Squares = mapWith((x) => x * x, a); | |
const EndWithOne = filterWith((x) => x % 10 === 1, Squares); | |
const UpTo1000 = untilWith((x) => (x > 1000), EndWithOne); | |
console.log(gather(Evens)); | |
console.log(gather(EndWithOne)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment