Last active
December 8, 2021 17:09
-
-
Save nikensss/13dd6a6a4c4f9c732eceeba2de00c347 to your computer and use it in GitHub Desktop.
Example of iterable iterators and async iterable iterators on TypeScript
This file contains hidden or 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
/** | |
* A silly class wrapping a number to demonstrate any type of object can be used | |
* when using IterableIterators and how to use the 'n' value when iterating over | |
* them. | |
*/ | |
class SpecialNumber { | |
private root: number; | |
constructor(root: number) { | |
this.root = root; | |
} | |
above() { | |
return this.root + 1; | |
} | |
below() { | |
return this.root - 1; | |
} | |
} | |
/** | |
* This class implements both the 'Symbol.asyncIterator' and the | |
* 'Symbol.iterator' to show how to create iterable classes in TypeScript. | |
* | |
* This example was built with TypeScript 4.5.2. Not sure how far back in | |
* versions compatibility goes. | |
*/ | |
class IterableClass { | |
private data: SpecialNumber[]; | |
constructor(data: number[]) { | |
this.data = data.map((n) => new SpecialNumber(n)); | |
} | |
/** | |
* This will let us iterate this class with the 'for await .. of' syntax. | |
* No need to implement any interface on the class. | |
* The '*' after the 'async' keyword allows us to use 'yield' inside this method. | |
*/ | |
async *[Symbol.asyncIterator](): AsyncIterableIterator<SpecialNumber> { | |
for (const n of this.data) { | |
yield await new Promise((res) => setTimeout(res, 250, n)); | |
} | |
} | |
/** | |
* This will let us iterate this class with the 'for .. of' syntax. | |
* No need to implement any interface on the class. | |
* The '*' allows us to use 'yield' inside this method. | |
*/ | |
*[Symbol.iterator](): IterableIterator<SpecialNumber> { | |
for (const n of this.data) { | |
yield n; | |
} | |
} | |
getName(): SpecialNumber[] { | |
return this.data; | |
} | |
} | |
(async () => { | |
const t = new IterableClass([1, 2, 3]); | |
// in this case, 'n' is of type 'SpecialNumber', so we can call any of its methods | |
for await (const n of t) { | |
console.log({ n: n.above() }); | |
} | |
console.log('in between for loops'); | |
// the same applies here | |
for (const n of t) { | |
console.log({ n: n.above() }); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment