Search code examples
javascriptbitwise-operators

Why do I need a bit wise Operator to access the last array element?


I have the following code that is supposed to find the intersection between two strings in an array like this ["1, 3, 4, 7, 13", "1, 2, 4, 13, 15"] It should give the result: 1,4,13

  function FindIntersection(strArr) { 

    const firstArr = strArr[0].split(", ");
    const secondArr = strArr[1].split(", ");

    let newArr = [];
    let i = 0;
    let j = 0;


    while(i < firstArr.length && j < secondArr.length) {
      let a = firstArr[i] | 0;
      let b = secondArr[j] | 0;
      if(a === b) {
        newArr.push(a);
        i++;
        j++;
      } else if(a > b) {
        j++;
      } else if (b > a) {
        i++;
      }
    }

    strArr = newArr.join(",");

    return strArr; 

}

When I do not use the bitwise operator | 0 the last element in the array is not accessed properly why? How does the bitwise operator solve this problem?


Solution

  • You don't need a bitwise operator explicitly, you just need to convert it to an integer. As mentioned in comments, it's just one way of triggering a cast of a string into an integer.

    typeof('str' | 0) === 'number'
    

    But that sucks, right, since 'str' there is probably a bug. I'd be more explicit and use:

    let a = parseInt(firstArr[i], 10);
    

    That will return NaN if it is not a valid integer, and NaN === NaN is false, so you won't accidentally add it to newArr.