[Javascript] Generator & Iterators exercise

Generator can run with for .. of and ..., which will only emit yield values 

For example:

function* count() {
    yield 1;
    yield 2;
    return 3;
}

for (const value of count()) {
   console.log(value) // 1, 2
}


console.log([...count()]) // [1, 2]

 

Iterator

Using [Symbol.iterator]()which should return next() function:

const range = {
    from: 1,
    to: 5,
    [Symbol.iterator]() {
        return {
             current: this.from,
             last: this.to,
             next() {
                 if (this.current <= this.last) {
                     return {done: false, value: this.current++}
                 } else {
                     return {done: true}
                 }
             }
        }
    }
}

console.log([...range]) // [1,2,3,4,5]

 

Or we can also just do geneator appraoch:

const range = {
    from: 1,
    to: 5,
    *[Symbol.iterator]() {
        for (let i = this.from; i <= this.to; i++) {
           yield i
        }
    }
}

console.log([...range]) // [1,2,3,4,5]

 

One usecase for geneator and iterator is that not overload the data, everytime can just load a small tunck of data to process with next() call instead of loading the whole data into memory

 

Delegating a yield

function* gen1() {
    yield 2;
    yield 3;
}

function* gen2() {
    yield 1;
    yield* gen1() // delegating a yiled*, yield* must used with iterable yiled* [2,3] 
    yield 4;
}

console.log([...gen2()]) // [1,2,3,4]

 

posted @   Zhentiw  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-03-13 [HTML5] Correctly Define Heading Levels of a Web Page
2020-03-13 [Functional Programming] Function modelling -- 3. Reader Monad
2020-03-13 [Functional Programming] 1. Function modelling -- Combine functions
2019-03-13 [Algorithm] Universal Value Tree Problem
2019-03-13 [HTML5] Using the focus event to improve navigation accessibility (nextElementSibling)
2019-03-13 [Javascript] Coding interview problem: Scheduler functional way
2018-03-13 [HTML 5] Atomic Relevant Busy
点击右上角即可分享
微信分享提示