Created
November 24, 2020 06:15
-
-
Save whal-e3/46fd29f1c6d0acac2abee56b81766d0e to your computer and use it in GitHub Desktop.
JS iterator/generator baiscs
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
// Iterator | |
function nameIterator(names) { | |
let nextIndex = 0; | |
return { | |
next: function () { | |
return nextIndex < names.length | |
? { value: names[nextIndex++], done: false } | |
: { done: true }; | |
} | |
}; | |
} | |
const namesArr = ['Jack', 'Jill', 'John']; | |
const names = nameIterator(namesArr); | |
console.log(names.next()); | |
console.log(names.next()); | |
console.log(names.next()); | |
console.log(names.next()); | |
// ------------------------------------------------ | |
// Generator | |
function* sayNames() { | |
yield 'Jack'; | |
yield 'Jill'; | |
yield 'John'; | |
} | |
const name = sayNames(); | |
console.log(name.next()); | |
console.log(name.next()); | |
console.log(name.next()); | |
console.log(name.next()); | |
// ID Creator | |
function* createIds() { | |
let index = 0; | |
while (index < 5) { | |
yield index++; | |
} | |
} | |
const gen = createIds(); | |
console.log(gen.next()); | |
console.log(gen.next()); | |
console.log(gen.next()); | |
console.log(gen.next()); | |
console.log(gen.next()); | |
console.log(gen.next()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment