[Solved] Run something once in a javascript recursive function


It’s often helpful to wrap a function used to evaluate something recursively in an outer function to make the API cleaner:

function factorial(n) {
  function compute(n) {
    if (n === 0 || n === 1)
      return 1;
    return n * compute(n - 1);
  }
  return compute(n || 1);
}

Now the n || 1 initialization happens once, when the inner compute() function is invoked.

Creating a wrapper like that is even more useful for some combinatorics algorithms (“find all combinations …” etc).

solved Run something once in a javascript recursive function