What does the tilde do in this javascript line?

I am trying to understand this line of code. What is minus and tilde to make r [e] ?:

r = {}
for (e of s)
    r[e] = -~r[e] // What is this specific line assigning?

for (e in r)
    if (r[e] == 1)
        return e
return '_'

The problem this code solves is this (a specific line is commented out):

Given the string s, find and return the first instance of a non-duplicate character in it. If not, return '_'.

I understand lines other than commented out.

+4
source share
2 answers

Tilde is that unary operatorwhich takes the correct expression, executes this little algorithm on it

-(N+1) // N is the expression right to the tilde

So, in your code, it increments r[e]by 1 (due to double negation).

See examples below:

console.log(~-2); // 1
console.log(~-1); // 0
console.log(~0);  // -1
console.log(~1);  // -2
console.log(~2);  // -3
Run codeHide result
+5
source

Tilde is a bitwise operator for the NOT operation.

, 32- (. IEEE_754-1985 . 0 1, 1 0.

, 5

00000000 00000000 00000000 00000101

~ 5 - ,

11111111 11111111 11111111 11111010

~ 5 (-6). 2 . , JavaScript, , . 2 X - (X + 1)

, , , .

  • (|)
  • (&)
  • NOT (~)
  • XOR (^)
  • LEFT SHIFT (< <)
  • RIGHT SHIFT ( → )
+2

Source: https://habr.com/ru/post/1694030/


All Articles