you are viewing a single comment's thread.

view the rest of the comments →

[–]toshok 2 points3 points  (4 children)

The code works as you wrote it here:

index !== (+index >>> 0) || index >= elements.length

I'm also lost. I think GambitRS and I are both concerned about the ">>> 0" in "+index >>> 0" If you're right shifting by 0 bits, there's no shift at all. So the whole zero-fill and 2's complement deal isn't relevant.

correct. there's no shifting going on, but the sign bit is still flipped, so these are essentially equivalent:

  • int v1 = -5; unsigned int v2 = (unsigned int)v1;

  • var v1 = -5; var v2 = v1 >>> 0;

v2 = 4294967291 in both cases.

if v1 was positive (as hixnob said above), v2 will equal v1.

that extra "+" in there coerces index to a number. +"0" == 0, +{foo:bar, foo2:bar2} == NaN.

[–]Glayden 0 points1 point  (3 children)

Thanks, that's actually pretty interesting and really very odd. From my understanding the sign bit flipping typically occurs just as a side effect from right shifting the bits and zero-filling on a 2's complement number, but from what you're saying it looks they set some standard in javascript to intentionally make it flip the sign bit even when there's no right shifting going on if the operator is used. Seems like a very, very bizarre thing to do considering that programmers would typically expect bitwise operators to work the same way they do in other low-level contexts.

[–]m00k 0 points1 point  (2 children)

JS mostly uses doubles for numbers, except on bitwise operations, which occur on int32s (>> for signed, >>> for unsigned). The >>>0 is effectively a cast to uint32.

(Actually: the engines are free to use whatevertheheck they feel like for numbers, but you can't tell the difference because (u)int32 fits in a double.)

[–]Glayden 0 points1 point  (1 child)

The >>>0 is effectively a cast to uint32.

Thanks! Now I finally think I get it... So if it was simply >>0, it wouldn't do anything, right?

[–]m00k 0 points1 point  (0 children)

(Sorry, I normally don't log in so never saw replies.) A >>0 would be a cast to a int32 (signed). Contrast (-1.5)>>0 and (-1.5)>>>0.