0

I get the error "Maximum call stack size exceeded error" when calling this recursive JavaScript.

This is my code:

var num = 12
,maxlength = 50;
var lengths = [5,6,7,8,4,4,5,6,3,3,2,2];

function knap(maxlength,num){
 if(maxlength==0) return 1;
 if(maxlength<0||(maxlength>0&&num<1)){
  return 0;
 }

 if(knap(maxlength-lengths[num],num-1)){
  console.log(lengths[num]+" ")
  return 1;
 }

 return knap(maxlength,num-1);
}

if(knap(maxlength,num)){
 console.log('Yes');
}else{
 console.log('No');
}

How can I figure out this?

Tim Penner
  • 3,551
  • 21
  • 36
Peter Lee
  • 3
  • 4
  • 2
    There's not much to figure out, you have a function that calls itself indefinitely, you pass in `50` so none of the if statements are true, it goes to the end, and calls the function again with `50` and the same thing happens over again. – adeneo Mar 22 '16 at 02:42
  • 1
    Did you get the terminating condition right? maxlength is same always – Denny Mathew Mar 22 '16 at 02:44
  • Aha, after the first iteration maxlength eq NaN. :) So terminating condition always false. – Vasyl Moskalov Mar 22 '16 at 02:57
  • Just curious, could you describe (informally) what your function is supposed to do? – Hunan Rostomyan Mar 22 '16 at 02:57
  • And Peter, IMHO you spend much less time to solve this issue if you insert something like `console.log(maxlength,num)` at first string of your function body. :) – Vasyl Moskalov Mar 22 '16 at 03:02

2 Answers2

1

When you first time call you function value of num is exceed the length of lengths array. So expression maxlength-lengths[num] in if(knap(maxlength-lengths[num],num-1)) is NaN. After that all your break recursion conditions alway is false. So, probably, you need to make first call as knap(maxlength,num-1).

Vasyl Moskalov
  • 4,242
  • 3
  • 20
  • 28
0

It means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit and it is most of the time because of recursion.

See Maximum call stack size exceeded error

Community
  • 1
  • 1
Abdul Mannan
  • 1,072
  • 12
  • 19