π Iterator
iterator is function which has next function
which returns object {done, value}
function genIterator(num) {
return {
next: function() { // β next!!
return {
done: true / false, // β done!!
value: some value // β value!!
}
}
}
}
For example??
function genIterator(num) {
let i = 0
return {
next: function() {
return {
done: false,
value: i
}
}
}
}
const it = genIterator()
β How to use it ??
console.log(it.next()) // 0
console.log(it.next()) // 1
console.log(it.next()) // 2
console.log(it.next()) // 3
(By the way this is used basic style of closure)

π "Javascript Closure" I think you can get what it is finally after reading this
Kaziu γ» May 18 '22
β How to set max value?
function genIterator(num) {
let i = 0
return {
next: function() {
if(i >= num) {
return {
done: true// β here!!
}
} else {
return {
done: false,
value: i
}
}
}
}
}
const it = genIterator(10)
let one = it.next()
while(!one.done) {
console.log(one.value)
one = it.next()
}
// 0 1 2 3 4 5 6 7 8 9
π Generator
generator is function to create iterator
Actually it's just simple version of iterator π€π€
function* generator() { //β asterisk !!
if(loop continue) {
yield value; //β keyword "yield"
} else {
return value;
}
}
function* β π€ what is this asterisk??
π it defines this function is GENERATOR !!!yield β π€ what is this??
π it returns {value, done}, like iterator
βΌ Let's make simple example
function* generator() {
yield 1
yield 2
return 3
}
const it = generator()
// β return {value, done} like iterator !!
console.log(it.next()) // {value: 1, done: false}
console.log(it.next()) // {value: 2, done: false}
console.log(it.next()) // {value: 3, done: true}
console.log(it.next()) // {value: undefined, done: true}
βΌ Let's transform counter function (genIterator function) by generator
function* genIterator(num = 10) {
let i = 0
while(i < num) {
yield i++
}
}
const it = genIterator(10)
let one = it.next()// β execute by next() like itarator !!!
while(!one.done) {
console.log(one.value)
one = it.next()
}
// 0 1 2 3 4 5 6 7 8 9
Generators are also iterable
function* alphabets() {
yield 'a'
yield 'b'
yield 'c'
}
for(let letter of alphabets()) {
console.log(letter)
}
// a b c
Top comments (0)