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?
-
4
It's not a "shorthand", it's two operators in a row (
-
and~
). – JJJ Commented May 17, 2013 at 16:56
3 Answers
Reset to default 4It 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
bees 11111110
for example, or in hexidecimal, 0x01
bees 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 piler or pressor to perform this optimization.
Bitwise inversion.
~0 == 0xFFFFFFFF == -1
~1 == 0xFFFFFFFE
Minus is arithmetic inversion. So result is 0 if indexOf failed (return -1)
The two operators are not a shorthand form of anything. ~
is bitwise negation, and -
is standard negation.
~foo.indexOf(bar)
is a mon shorthand for foo.contains(bar)
. Because the result is used in an if
statement, the -
sign immediately after is pletely 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 peting in a code golf where you're not allowed to use the digit 1
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744769817a4592690.html
评论列表(0条)