Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function simpleIterator() {
const iterator = {
next() {
return {
value: "Hello, I'm an iterator",
done: true,
};
},
};
const result = iterator.next();
console.log(result.value);
console.log(result.done);
}
function helloWorld() {
const words = ["Hello", "World"];
let index = 0;
const iterator = {
next() {
return {
value: words[index++],
done: index === words.length + 1,
};
},
};
let result = iterator.next();
console.log(result.value, result.done);
result = iterator.next();
console.log(result.value, result.done);
result = iterator.next();
console.log(result.value, result.done);
}
function helloWorldIterable() {
const words = ["Hello", "World"];
let index = 0;
const iterator = {
next() {
return {
value: words[index++],
done: index === words.length + 1,
};
},
};
const iterable = {
[Symbol.iterator]() {
return iterator;
},
};
for (let word of iterable) {
console.log(word);
}
}
function iteratorAndIterable() {
const iteratorAndIterable = {
next() {
// ...
},
[Symbol.iterator]() {
return this;
},
};
}
function generatorExample() {
function* generateHelloWorld(name) {
yield "Hello";
yield "World";
yield name;
}
const generator = generateHelloWorld("Tomasz");
for (let word of generator) {
console.log(word);
}
}
generatorExample();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment