javascript 使用trampolines来管理JavaScript中的大型递归循环

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 使用trampolines来管理JavaScript中的大型递归循环相关的知识,希望对你有一定的参考价值。

// recursion
// iterative way
const sumBelow = number => {
  let result = 0;
  
  for(let i = 0; i <= number; i++) {
    result += i;
  }
  
  return result;
}

// the recursive way
const sumBelow  = (number, sum = 0) => (
  number === 0
    ? sum
    : sumBelow(number - 1, sum + number)
)

// possible Problem with recursion above:
sumBelow(100000); // => Uncaught RangeError: Maximum call stack size exceeded

// Large recursive loops with trampolines
const trampoline = fn => (...args) => { // takes a function (fn) as argument (this is the
  let result = fn(...args);             // recursive function it is going to wrap) and
                                        // returns a new function. Within this new function,
  while (typeof result === 'function') {// the recursive function is called. The loop runs as
    result = result();                  // fn returns another function. Once fn resolves into
  }                                     // a value, we stop running the loop and return the value.
  
  return result;
}

// The recursive function as to be slightly modified in order to be used by the
// trampoline function:
const sumBelowRec = (number, sum = 0) => (
  number === 0
    ? sum
    : () => sumBelowRec(number - 1, sum + number) // The recursive portion now returs an anonymus
);                                                // function and can be managed by the while-loop
                                                  // of the trampoline function
// Last step: wrapping sumBelowRec in the original function
const sumBelow = trampoline(sumBelowRec);
sumBelow(100000); // => 5000050000

以上是关于javascript 使用trampolines来管理JavaScript中的大型递归循环的主要内容,如果未能解决你的问题,请参考以下文章

html jsPatterns.recur.trampoline.js

cf1491C. Pekora and Trampoline

CodeForces - 1491C Pekora and Trampoline(差分+贪心)

Codeforces Global Round 13- C.Pekora and Trampoline - 贪心

什么是蹦床功能?

Air Track Mat