Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 408
Dream_Cap Avatar asked Mar 06 '23 19:03

Dream_Cap


1 Answers

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
like image 76
void Avatar answered Mar 19 '23 10:03

void