Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript Generators #14

Open
vivipure opened this issue Jun 24, 2022 · 0 comments
Open

JavaScript Generators #14

vivipure opened this issue Jun 24, 2022 · 0 comments

Comments

@vivipure
Copy link
Owner

vivipure commented Jun 24, 2022

迭代器

JS 中迭代器是指包含 next 方法的对象, next 方法返回一个包含 value 和 done 键值的对象。

a.next() // {value: 1, done: false}
a.next() // {value: 2, done: false}
a.next() // {value: undefined, done: true}

生成器

生成器 是 一种类型的迭代器, 生成器函数返回一个生成器对象,这个对象是可迭代的

function * genFunction() {
     yield 1;
}
const g = genFunction()
g.next() // value: 1, done: false
g.next() // value: undefined , done: true

自定义迭代器

const customIterator = {
    [Symbol.iterator]: function * () {
        let i = 0;
        while(i++ < 10) {
             yield i
       }
    }
}

利用 [Symbol.iterator] 我们可以实现直接的迭代对象,该对象可以通过 for ... in... 进行遍历

yield 传值

当我们在生成器对象next 方法传入参数时,当前的 yield 会变成我们传入的参数

function * listener() {
  while(true) {
     let msg = yield
     console.log(msg)
  }
}
let l = listener()
l.next(1) // 1
l.next(2) // 2

纤程

纤程 是 更小的线程,在JS中,可以通过 generator 实现纤程的效果

TODO:demo

惰性求值

利用yield 结合 无限循环, 我们可以通过其他函数调用生成器函数,生产我们想要的值。实际上函数内部使用了 while(true) 的语法,但是执行线程不会进入死循环,十分的有趣。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant