I have a recursive function written in Javascript, which is giving RangeError because of excessive deep recursion. Hence, I have used trampolining to make it tail-optimized. This has wrapped the function call in a while loop and I have gotten rid of RangeError. But I need to handle thrown exception inside the recursive function (go back one level and do some corrective processing). I am not sure how to handle this kind of situation, while using trampolining.
My original recursive function (simplified for illustration):
function process (val, level){
if(val < 0 ){
throw new negativeException(val);
}
for(var i=0; i< num; i++){
try{
//do some processing on val
process (val, level+1);
return;
}
catch(e){
//do some different processing on val and use i as well
}
}
}
function process (val, level)
My updated recursive function using trampolining (ref: Understanding recursion in functional JavaScript programming)
function trampoline(f) {
try{
while (f && f instanceof Function) {
f = f();
}
} catch(e) {
//catching exception in trampoline
}
return f;
}
function callProcess(val, level){
function process(val, level){
if(val < 0 ){
throw new negativeException(val);
}
for(var i=0; i< num; i++){
try{
//do some processing on val
return process.bind(null, val, level+1); /updated recursive call
}
catch(e){
//do some different processing on val and use i as well
}
}
}
return trampoline(process.bind(null, pstate,level));
}
function callProcess(val, level)
With the updated code, I am able to avoid RangeError as long as val
is not negative and no exception is being thrown. But when val
goes negative and exception is thrown, I am directly going to the trampoline catch block. But I need to go back to the catch block of process() one level up.
Can you suggestion how I can achieve that? Thanks for your help! I have checked out some related posts, but unable to figure out the solution I need.