Study the original function.
function factorial(n) { return n > 1 ? n * factorial(n - 1) : 1; } console.log(factorial(5)); // 120
Convert recursive calls into tail calls
function factorial(n, result = 1) { return n > 1 ? factorial(n - 1, result * n) : result; } console.log(factorial(5)); // 120
Introduce a one-shot loop around the function body.
function factorial(n, result = 1) { while (true) { return n > 1 ? factorial(n - 1, result * n) : result; break; } } console.log(factorial(5)); // 120
Replace all recursive tail calls f(x=x1, y=y1, ...) with [x, y, ...] = [x1, y1, ...]; continue.
f(x=x1, y=y1, ...)
[x, y, ...] = [x1, y1, ...]; continue
function factorial(n, result = 1) { while (true) { if (!(n > 1)) return result; [n, result] = [n - 1, result * n]; continue; break; } } console.log(factorial(5)); // 120
Tidy up
function factorial(n) { let result = 1; while (n > 1) [result, n] = [result * n, n - 1]; return result; } console.log(factorial(5)); // 120
Make more idiomatic
function factorial(n) { let result = 1; for (; n > 1; result *= n, n -= 1); return result; } console.log(factorial(5)); // 120
If you like that rabbit hole take a look at recursion and Recursion? We don't need no stinking recursion!.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Study the original function.
Convert recursive calls into tail calls
Introduce a one-shot loop around the function body.
Replace all recursive tail calls
f(x=x1, y=y1, ...)
with[x, y, ...] = [x1, y1, ...]; continue
.Tidy up
Make more idiomatic
If you like that rabbit hole take a look at recursion and Recursion? We don't need no stinking recursion!.