Reputation: 1053
smallestInteger = (stack,numbers,k) => {
if (stack.length == 0){
stack.push(numbers[k]);
}
if (numbers[k] <= stack[stack.length-1]){
stack.pop();
stack.push(numbers[k]);
}
console.log(`stack is ${stack}`)
console.log("k:" + k);
return (k == 0) ? stack[stack.length-1] : smallestInteger(stack,numbers,k-1);
}
var smallestInteger = function(numbers) {
let stack = [];
let smallest = smallestInteger(stack ,numbers,numbers.length - 1);
return `the smallest integer is ${smallest}`;
}
var testCases = [[10,2,5,7,15,9], [1,2,3,4]];
for (let testCase of testCases){
console.log(smallestInteger(testCase));
}
Running > node smallestInteger.js
gives this error:
RangeError: Maximum call stack size exceeded
at smallestInteger (smallestInteger.js:17:31)
at smallestInteger (smallestInteger.js:19:17)
at smallestInteger (smallestInteger.js:19:17)
at smallestInteger (smallestInteger.js:19:17)
at smallestInteger (smallestInteger.js:19:17)
at smallestInteger (smallestInteger.js:19:17)
at smallestInteger (smallestInteger.js:19:17)
at smallestInteger (smallestInteger.js:19:17)
at smallestInteger (smallestInteger.js:19:17)
at smallestInteger (smallestInteger.js:19:17)
fyi the code is not reaching the console.log print statements so how do I resolve this?
The two smallestInteger
functions have different constructors (first has 1 argument, other has 3) like an override, so I dont assume the they are replacing each other. Where are you seeing it get 2 arguments, it gets 3 arguments as expected. Finally, smallestInteger
function is calling the smallestInteger
helper function which does have an exit condition after the ?
that is k == 0
so it should not go on forever. Still getting the same error
Upvotes: 1
Views: 68
Reputation: 51
Javascript does not allow to overload functions. For this you need to be creative. For example:
function smallestInteger(stack,numbers,k){
if (arguments.length == 1) {
numbers = stack;
stack = [];
let smallest = smallestInteger(stack ,numbers,numbers.length - 1);
return `the smallest integer is ${smallest}`;
}
if (stack.length == 0){
stack.push(numbers[k]);
}
if (numbers[k] <= stack[stack.length-1]){
stack.pop();
stack.push(numbers[k]);
}
return (k == 0) ? stack[stack.length-1] : smallestInteger(stack,numbers,k-1);
}
var testCases = [[10,2,5,7,15,9], [1,2,3,4]];
for (let testCase of testCases){
console.log('testCase : ', testCase);
console.log(smallestInteger(testCase));
}
Upvotes: 1