模拟es6的generator

//es6 

   

function* letters() {
  console.log('a');
  yield 'a';
  console.log('b');
  yield 'b';
  while (true) {
    console.log('c');
    yield 'c';
  }
}

 //polyfilling es5

  

function letters() {
  var state = 0;
  return {
    next: function() {
      switch (state) {
        case 0:
          console.log('a');
          state = 1;
          return {
            value: 'a', // Return the first yielded value.
            done: false
          };
        case 1:
          console.log('b');
          state = 2;
          return {
            value: 'b', // Return the second yielded value.
            done: false
          };
        case 2:
          console.log('c');
          return {
            value: 'c', // Return the third yielded value... forever.
            done: false
          };
      }
    }
  };
}

  简述:上述方法只是 通过肉眼观察原函数 的内部代码 来编写polyfilling 的代码,可以从原函数的3个yield和polyfilling之后的3个case可以看出,

       故猜想:真正的polyfill应该是代码根据原函数生成yield,先将原函数toString,用正则匹配来分析yield, 对于原函数里面的循环(for while ....),应对应生成迭代器

      上述猜想待完善中......

     代码搬运至  https://gu.illau.me/posts/polyfilling-generators/

posted @ 2020-05-24 13:53  wangnima666  阅读(213)  评论(0编辑  收藏  举报