Dream_Cap
Dream_Cap

Reputation: 2302

What is the tilde doing in this line of javascript?

I am trying to understand this line of code. What is the minus and tilde doing to 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(specific line is commented):

Given a string s, find and return the first instance of a non-repeating character in it. If there is no such character, return '_'.

I understand the other lines except the commented one.

Upvotes: 4

Views: 119

Answers (2)

hashedram
hashedram

Reputation: 934

Tilde is the bitwise operator for NOT operation.

It takes in a number as operand, converts it into a 32 bit integer (refer IEEE_754-1985 and flips all the bits. 0 becomes 1, 1 becomes 0.

For example, if the number 5 is represented by

00000000 00000000 00000000 00000101

The number ~5 is the above, with the bits flipped

11111111 11111111 11111111 11111010

The decimal value of ~5 is (-6). This is also known as 2's complement. Since the most significant bits, which represent the sign of the number in JavaScript are flipped, the sign will always change. 2's complement causes the value of X to change to -(X+1)

Certain applications like engines, use bitwise data structures and bitwise operations play a role in those.

  • Bitwise OR (|)
  • Bitwise AND (&)
  • Bitwise NOT (~)
  • Bitwise XOR (^)
  • Bitwise LEFT SHIFT (<<)
  • Bitwise RIGHT SHIFT (>>)

Upvotes: 2

void
void

Reputation: 36703

Tilde is a unary operator that takes the expression to its right performs this small algorithm on it

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

So in your code it is incrementing r[e] with 1 (because of double negation).

See the examples below:

console.log(~-2); // 1
console.log(~-1); // 0
console.log(~0);  // -1
console.log(~1);  // -2
console.log(~2);  // -3

Upvotes: 5

Related Questions