Tech Solvr
Tech Solvr

Reputation: 505

while loop running forever in JavaScript

Following is my code, in which I am trying to reduce the size of each array item by 2 and once the particular value of an array becomes 0 or -1 I will replace it with undefined.

Example -

Input - [5,4,4,2,2,8]

Output -

Array            Non Blank Values    
5 4 4 2 2 8          6        
3 2 2 _ _ 6          4        
1 _ _ _ _ 4          2        
_ _ _ _ _ 3          1        
_ _ _ _ _ _        DONE   

Code (Somehow its going as an infinite loop)-

var arr = [5,4,4,2,2,8]; // 6 4 2 1
var num = 0;
itemNum = countItemNotUndefined(arr);

function makeItemUndefine(arr) {
    return arr.map(function(x){
        x = x - 2;
        return x ==0 || x == -1 ? undefined : x;
    })
}

function countItemNotUndefined(arr) {
    var itemLength = 0;
    arr.map(function(x){
        if(x !== undefined)
            itemLength++;   
    })
    return itemLength;
}

while(itemNum != 0) {
    num ++;
    var result = makeItemUndefine(arr);
    itemNum = countItemNotUndefined(result);
}

console.log("Number is ", num);

Let me know what I am doing wrong here.

Upvotes: 0

Views: 375

Answers (1)

mash
mash

Reputation: 15229

The problem is that you're calling makeItemUndefine on arr, which doesn't change, since you assign the result to a different variable called result. So you aren't actually reducing the numbers in the array over time.

The correct solution would be:

while(itemNum != 0) {
    num ++;
    arr = makeItemUndefine(arr);
    itemNum = countItemNotUndefined(arr);
}

Another problem with the code is the fact that you're trying to subtract from undefined numbers, which turns them, into NaN's. There are two solutions to this, either check for NaN inside of countItemNotUndefined, or check for undefined inside of the map.

Upvotes: 3

Related Questions