💎 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)