I have been trying to understand Tail call optimization
in context of JavaScript and have written the below recursive and tail-recursive methods for factorial()
.
Recursive:
function factorial (n) {
if (n < 2) {
return 1;
} else {
return n * factorial(n-1);
}
}
Tail-recursive:
function factorial (n) {
function fact(n, acc) {
if (n < 2) {
return acc;
} else {
return fact(n-1, n * acc);
}
}
return fact(n, 1)
}
But I am not sure if the tail-recursive
version of the function will be optimised by JavaScript compiler as it is done in other languages like Scala etc. Can someone help me out on this one?
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…