Reputation: 151
i try to make recursive function but always got error. Please somebody tell me why i'm always got "Maximum call stack exceeded" and show me the right one. I write input and expect output in code below:
function oscillated(N) {
let output = '';
const i = N > 0 ? -5 : 5;
output+= oscillated(N+i);
if(output === N) {
return ' ' + N + i;
}
return output;
}
// input between 0 - 100
console.log(oscillated(16));
// expect output 16 11 6 1 -4 1 6 11 16
console.log(oscillated(10));
// expect output 10 5 0 5 10
Noted: You can add another parameter if it needed.
Upvotes: 0
Views: 749
Reputation: 2375
The reason why you were getting this error is you have a problem with recursion in JavaScript code at line output+= oscillated(N+i); which is causing infinite recursions.
Recursion is a loop that repeats itself, but it should have the terminal condition to prevent an endless loop. Every time a function is called, an execution context is created. Hence, they are stacked together and increase as the recursion goes deeper.
The Call Stack is what a program uses to keep track of method calls. When you enter a function, an entry for that function is pushed onto the Call stack and when you exit from the function, that same entry is popped from the Call Stack. Each method call creates its own stack frame, taking up space on the call stack. That's important because it can impact the space complexity of an algorithm, especially when we use recursion. If you provide too many arguments or caught inside any unhandled recursive call. You will encounter Maximum call stack size exceeded error.
However, normal recursion can possibly generate "Maximum call stack size exceeded" error if it calls a recursive function over and over again, as the memory that can be allocated for use is not unlimited. So, the call stack grows until it hits a maximum limit or memory exhaustion and fails with this error message.
So, whenever you are trying to code a recursive function then you'll need a terminal condition/case that stops the function to invoke itself. setTimeOut functions also help in handling such cases.
Upvotes: 0
Reputation: 151
Thank you all for the suggestion.
function oscillated(N, A = N, B) {
const i = -5;
let output = A;
if(A <= 0) return output+= ' ' + oscillated(N, A-i, A-i);
if(B) {
if(B === N) return output;
else if(B < N) return output+= ' ' + oscillated(N, A-i, B-i)
}
return output+= ' ' + oscillated(N, A+i);
}
console.log(oscillated(16));
console.log(oscillated(10));
Upvotes: 1