I am looking at SocketIO source code and it has this statement:
if (-~manager.get('blacklist').indexOf(packet.name)) {
What does -~ shorthand mean here?
I am looking at SocketIO source code and it has this statement:
if (-~manager.get('blacklist').indexOf(packet.name)) {
What does -~ shorthand mean here?
Bitwise inversion.
~0 == 0xFFFFFFFF == -1
~1 == 0xFFFFFFFE
Minus is arithmetic inversion. So result is 0 if indexOf failed (return -1)
It is appears to be a trick for:
if(manager.get('blacklist').indexOf(packet.name) !== -1)
As mentioned by others ~ is bitwise negation which will flip the binary digits. 00000001 becomes 11111110 for example, or in hexidecimal, 0x01 becomes 0xFE.
-1 as a signed int 32 which is what all bitwise operators return (other than >>> which returns a unsigned int 32) is represented in hex as 0xFFFFFFFF. ~(-1) flips the bits to result in 0x00000000 which is 0.
The minus simply numerically negates the number. As zzzBov mentioned, in this case it does nothing.
-~(-1) === 0
And
~(-1) === 0
The code could be changed to:
if(~manager.get('blacklist').indexOf(packet.name))
But, in my opinion, characters aren't at such a premium so the longer version, which is arguably a bit more readable, would be better, or implementing a contains method would be even better, this version is best left to a JavaScript compiler or compressor to perform this optimization.
The two operators are not a shorthand form of anything. ~ is bitwise negation, and - is standard negation.
~foo.indexOf(bar) is a common shorthand for foo.contains(bar). Because the result is used in an if statement, the - sign immediately after is completely useless and does nothing of consequence.
-~ together is a means to add 1 to a number. It's generally not useful, and would be better expressed as + 1, unless you're competing in a code golf where you're not allowed to use the digit 1