Skip to content

Instantly share code, notes, and snippets.

@carbide-public
Created March 24, 2017 00:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save carbide-public/57d9d3c382a9f8af569c823c8fa8e345 to your computer and use it in GitHub Desktop.
untitled
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