Another (and perhaps more enjoyable) solution would be to use the strengths of JS functional programming and use a high-order function to maintain the entire depth of housekeeping outside the main function. Consider, for example, the following classic example:
function fac(n) { if(n < 3) return n; return n * fac(n - 1); }
We want this to break the recursion when it goes deeper than the given value. Let the wrapper code:
function wrapDepth(fn, max) { var depth = 0 return function() { if (++depth > max) throw "Too much recursion" var out = fn.apply(null, [].slice.call(arguments, 0)) depth--; return out; } }
Create a wrapper with maximum depth = 20:
fac = wrapDepth(fac, 20)
and test:
console.log(fac(10)) // 3628800 console.log(fac(100)) // Too much recursion
Please note that we have not made any changes to the main function of fac , but, nevertheless, its depth of recursion is now under control.
georg
source share