Skip to content

Instantly share code, notes, and snippets.

@Fredkiss3
Created July 2, 2022 02:21
Show Gist options
  • Save Fredkiss3/67235bef9a65710521b698c3e1602e3c to your computer and use it in GitHub Desktop.
Save Fredkiss3/67235bef9a65710521b698c3e1602e3c to your computer and use it in GitHub Desktop.
Custom Range implementation in TypeScript with iterator
class MyRange implements Iterable<number> {
public readonly [Symbol.iterator]: () => Iterator<number> = function* () { }
constructor(private readonly start: number,private readonly end: number,private readonly step: number = 1) {
if (step === 0) return
if (step < 0) step = -step
if (start > end) this[Symbol.iterator] = function* () {
for (let i = start; i >= end; i -= step) yield i
}
else this[Symbol.iterator] = function* () {
for (let i = start; i <= end; i += step) yield i
}
}
}
for (const value of new MyRange(42,35,2)) console.log(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment