TailCallOptimization (TO01)
1: "use strict";
2: function factorial(n, accumulator = 1) {
3: if (n === 0) {
4: return accumulator;
5: }
6: return factorial(n - 1, n * accumulator); // Tail call (last operation is the recursive call)
7: }
8: console.log(factorial(50)); // Output: 3.0414093201713376e+64 (should work without stack overflow)
9: console.log(factorial(500)); // Output: Infinity (should work without stack overflow)
3.0414093201713376e+64 Infinity
ES6 context:
Comments (
)
)
Link to this page:
http://www.vb-net.com/JavascriptES6/TO01.htm
|
|