Last active
November 10, 2018 18:17
-
-
Save breckwagner/1169b4886bb7044e980d1ece5d12d8b5 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
/** | |
* @name range | |
* @description | |
* @async | |
* @generator | |
* @function | |
* @param {Object} [context=this] - | |
* @param {number} context.start - The value to use to begin the sequence. | |
* @param {number} context.stop - The value to use to stop the sequence. | |
* @param {number} context.step - The value to increment n by on each yield | |
* @yields {number} n - The next number in the sequence. | |
* @return {Promise<T>} this | |
*/ | |
export default function range(context = this) { return new Range(context)} | |
class Range { | |
constructor(context = this) { | |
const {start=0, stop=Infinity, step=1} = context; | |
Object.assign(this, {start, stop, step, next: this.next.bind(this)}); | |
} | |
[Symbol.isConcatSpreadable]() { | |
return ({ | |
'number': stop.isFinite(), | |
'bigint': true, | |
}[stop]) | |
} | |
get[Symbol.toStringTag]() {return 'Range'} | |
async * [Symbol.asyncIterator]() {yield* this.next()} | |
* [Symbol.iterator]() {yield* this.next()} | |
* next() { | |
for (let n = this.start; (Math.sign(this.stop - n) == Math.sign(this.step)); n += this.step) { | |
yield n; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment