ES6学习笔记

ES6学习笔记4.5-关于自己实现尾递归优化的代码理解

2018-08-15  本文已影响0人  whowhenhowxxx
function tco(f) {
  var value;
  var active = false;
  var accumulated = [];

  return function accumulator() {
    accumulated.push(arguments);
    if (!active) {
      active = true;
      while (accumulated.length) {
        value = f.apply(this, accumulated.shift());
      }
      active = false;
      return value;
    }
  };
}

var sum = tco(function(x, y) {
  if (y > 0) {
    return sum(x + 1, y - 1)
  }
  else {
    return x
  }
});

sum(1, 100000)
// 100001

这段代码的理解关键:

此时 accumulated = [] value = undefined active = true

此时 accumulated = [2,99] value = undefined active = true

上一篇 下一篇

猜你喜欢

热点阅读