Skip to content

Instantly share code, notes, and snippets.

@Yoshyn
Last active May 11, 2023 11:46
Show Gist options
  • Save Yoshyn/f72813d8209921bafd8fef26fabd693b to your computer and use it in GitHub Desktop.
Save Yoshyn/f72813d8209921bafd8fef26fabd693b to your computer and use it in GitHub Desktop.
Some simple of writing iterator in javascript. Produce ce same result.
//Equivalence 1 :
async function * iterableFct() {
let i = 0;
while (i < 2) yield ++i;
}
const iterable = iterableFct();
await iterable[Symbol.asyncIterator]().next(); // 1
await iterable[Symbol.asyncIterator]().next(); // 2
for await (const response of iterable) {
console.log(response);
}
//Equivalence 2 :
const iterableObject = {
i: 0,
async * [Symbol.asyncIterator]() {
while (this.i < 2) yield ++this.i;
},
};
const iterable2 = iterableObject[Symbol.asyncIterator]();
await iterable2[Symbol.asyncIterator]().next(); // 1
await iterable2[Symbol.asyncIterator]().next(); // 2
for await (const response of iterable2) {
console.log(response);
}
//Equivalence 3 :
const iterableObject2 = {
i: 0,
[Symbol.asyncIterator]() {
return {
next: () => {
if (this.i < 2) {
return { value: ++this.i, done: false };
} else {
return { done: true };
}
},
return: () => {
return { done: true };
},
[Symbol.asyncIterator]() { return this; },
};
},
};
const iterable3 = iterableObject2[Symbol.asyncIterator]();
await iterable3[Symbol.asyncIterator]().next();
await iterable3[Symbol.asyncIterator]().next();
for await (const response of iterable3) {
console.log(response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment