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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With