Generator函数实现斐波那契数列

ES6 中 generator生成器函数

特点:

  • 调用generator函数返回一个迭代器(iterator)对象
  • 通过next()可以分段执行,手动控制执行阶段
  • yield 表示暂停执行, renturn 表示结束执行
  • next() 中可以传参数,可以从外部向内部传值
  • for of 语句可以自动遍历迭代器对象,不需要显示调用next()方法
function *g(){
            var o = 1
          let m = yield o++
            console.log(m)
            // return 3 // 设置return,后面的值不返回
            yield o++
            yield o++  
        }
var gene = g()
gene.next() // {value: 1, done: false}
gene.next('传入的值') // '传入的值' ; {value: 2, done: false}
gene.next() // {value: 3, done: false}
gene.next() // {value: undefined, done: true}

//使用for of   调用
 for(let v of gene){
  console.log(v)
}
// 1
// 2
// 3
实现斐波那契数列

斐波那契数列,就是从第三个数开始,当前值为 前两个值之和
0,1,1,2,3,5,8...

// 递归实现
function fibonacci(m){
  if(m<2)return m
  return fibonacci(m-1) + fibonacci(m-2)
}
// 优化 缓存 空间换时间
function fibonacci2(m){
let cache = [1,1]
  //if(m<2)return m
  if(cache[m]) return cache[m]
  cache[m] = fibonacci(m-1) + fibonacci(m-2)
}

// 动态规划实现
function fibdp(n){
//递归是自上向下
// 动态规划是自下向上
let dp = [1, 1]
for(let i =3; i<=n; i++) {
  dp[i] = dp[i-1] + dp[i-2]
}
return dp[n]
}

// generator实现 遍历
function * gene(){
  let [prev, curr] = [0, 1]
  for(;;){
    [prev, curr] = [curr, prev + curr]
    yield curr
  }
}
for(let n of gene()){
  if(n> 1000){
    break
  }
  console.log(n)
}
// 1
// 2
// 3
// 5
// 8
// 13
// 21
// 34
// 55
// 89
// 144
// 233
// 377
// 610
// 987
generator实现异步编程

实现状态机,不使用时被挂起
同步化写法

function request(url){
  $.get(url, function(){res}{
    it.next(res) // 成功则调用下一个执行,并将数据作为参数传入内部
    // 很妙,类似koa2的中间件洋葱机制,也是next()调用下一个
  })
}

function * ajaxs(){
  console.log(yield request('a.html'))
  console.log(yield request('b.html'))
  console.log(yield request('c.html'))
}
var it = ajaxs()
it.next()
// a.html
// b.html
// c.html


generator 原理

状态机
代码被转换为switch块
generator 函数实现了一个惰性序列状态机

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容