Barte
Barte

Reputation: 306

if statement evaluates incorrectly

function ipsBetween(start, end){
    var count = 0;
    for(var i = 0; i < 4; i++) {
      if(start.split('.').slice(i, i + 1) != end.split('.').slice(i, i + 1)) {
       count++;
      }
    }
    return count;
}

I am trying to find all possible IP's between a range. The above code is just a starting. I was trying to split the IP in pieces and check if they are equal or not. While I was doing so, interesingly even if the values are equal it evaluates the if statement as true and increases the count. Here is my test case:

ipsBetween("10.0.0.0", "10.0.0.50")

This test case returns 4, whereas it should return 1. I don't know why this is happening. I implicity looked the values of start.split('.').slice(i, i + 1) and end.split('.').slice(i, i + 1) and the first three element is seem to be equal.

Upvotes: 1

Views: 86

Answers (3)

brso05
brso05

Reputation: 13222

You are comparing arrays not strings you want to compare the string values try this instead:

function ipsBetween(start, end){
    var count = 0;
    for(var i = 0; i < 4; i++) {
      if(start.split('.').slice(i, i + 1)[0] != end.split('.').slice(i, i + 1)[0]) {
       count++;
      }
    }
    return count;
}
console.log(ipsBetween("10.0.0.0", "10.0.0.50"));

The problem is the array objects returned won't equal each other because they are not the same array ie. they are not located at the same spot in memory...

Upvotes: 0

6502
6502

Reputation: 114481

The reason is that operator != when comparing two list objects will return true if they're not the very same object: split returns a list of strings but slice(i, i+1) will return a list of length 1.

This means that you're comparing ["10"] with another ["10"] and they're two different list objects, so != will return true.

If you just compare the contents using x.slice(".")[i] instead of using slice then the result is what you were expecting.

PS: The operator != of Javascript is terrible and you should not use it and prefer instead !==. It would be the same in this case, but it's much nicer to work with because it doesn't do crazy things when the two types are different.

PS2: Seems a good idea to split the strings at each iteration?

Upvotes: 1

Pointy
Pointy

Reputation: 413709

There's really no need to use .slice() here. (That's what's causing the problem: .slice() returns an array, and two different arrays will never be equal to each other.) Split the strings first and then just use array indexing:

var count = 0;
start = start.split("."); end = end.split(".");
for (var i = 0; i < start.length; ++i)
  if (start[i] != end[i])
    count++;
return count;

Upvotes: 2

Related Questions