Skip to content

Instantly share code, notes, and snippets.

@devsnek
Last active December 27, 2018 19:32
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 devsnek/230919934eff442a31f9e3116a752c68 to your computer and use it in GitHub Desktop.
Save devsnek/230919934eff442a31f9e3116a752c68 to your computer and use it in GitHub Desktop.
'use strict';
const IteratorPrototype = Object.getPrototypeOf(
Object.getPrototypeOf(
[][Symbol.iterator](),
),
);
const AsyncIteratorPrototype = Object.getPrototypeOf(
Object.getPrototypeOf(
async function* test() {}, // eslint-disable-line no-empty-function
).prototype,
);
const positiveRangeTest = (n, stop) => n < stop;
const negativeRangeTest = (n, stop) => n > stop;
const Iterator = {
prototype: IteratorPrototype,
asyncPrototype: AsyncIteratorPrototype,
of(...items) {
return items[Symbol.iterator]();
},
* range(start, stop, step = 1) {
const test = step >= 0 ? positiveRangeTest : negativeRangeTest;
for (let i = start; test(i, stop); i += step) {
yield i;
}
},
};
Iterator.asyncPrototype.filter = async function* filter(cb) {
for await (const item of this) {
if (await cb(item)) {
yield item;
}
}
};
Iterator.prototype.filter = function* filter(cb) {
for (const item of this) {
if (cb(item)) {
yield item;
}
}
};
Iterator.asyncPrototype.map = async function* map(cb) {
for await (const item of this) {
yield await cb(item);
}
};
Iterator.prototype.map = function* map(cb) {
for (const item of this) {
yield cb(item);
}
};
Iterator.asyncPrototype.reduce = async function reduce(reducer, start) {
let final = start;
for await (const item of this) {
final = await reducer(final, item);
}
return final;
};
Iterator.prototype.reduce = function reduce(reducer, start) {
let final = start;
for (const item of this) {
final = reducer(final, item);
}
return final;
};
Iterator.asyncPrototype.collect = async function collect() {
const out = [];
for await (const item of this) {
out.push(item);
}
return out;
};
Iterator.prototype.collect = function collect() {
const out = [];
for (const item of this) {
out.push(item);
}
return out;
};
global.Iterator = Iterator;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment