Skip to content

Instantly share code, notes, and snippets.

@breckwagner
Last active November 10, 2018 18:17
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 breckwagner/1169b4886bb7044e980d1ece5d12d8b5 to your computer and use it in GitHub Desktop.
Save breckwagner/1169b4886bb7044e980d1ece5d12d8b5 to your computer and use it in GitHub Desktop.
/**
* @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