I'm working on an algorithm where you are supposed to add 2 integers without using a + or -. So I took the two arguments, stuck them in an array, applied a forEach and incremented a counter by one as each element counted it's way down to 0. As such.
function test(a, b){
var array = [], counter = 0;
array.push(a,b);
array.forEach(function(element){
while (element > 0) {
counter ++;
element --;
}
})
return counter
}
This works fine. However, when I ran it through leetCode, one of it's test cases had a negative number. I erroneously assumed all cases would be positive. I rewrote the algorithm like this, to account for negatives.
function test(a, b){
var array = [], counter = 0;
array.push(a,b);
console.log(array);
array.forEach(function(element){
if (element > 0){
while (element > 0) {
counter ++;
element --;
}
} else if (element < 0) {
while (element < 0);
counter --;
element ++;
}
})
return counter
}
This works fine on paper, but it gets stuck in a loop when I run it in my terminal. At least I think it does. No error messages are displayed and I've consoled logged all the variables in every spot I can think off, and instead of having endlessly streaming console log numbers, which is what usually happens when I accidentally create an infinite loop, the cursor just sits there until I hit ctrl + c.
Any ideas what is causing this weird behavior? When I test it with
console.log(text(1,-1))
I would expect a return of 0,
Apparently it worked all along other then poorly placed brackets and typos. Thanks!