Last active
December 27, 2018 19:32
-
-
Save devsnek/230919934eff442a31f9e3116a752c68 to your computer and use it in GitHub Desktop.
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'; | |
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