TIL - Using ~ with Array.indexOf
Matthew Foley
Posted on May 31, 2020
I was playing with the bonjour package this morning, and when looking through the code, I noticed this function block:
function unique () {
var set = []
return function (obj) {
if (~set.indexOf(obj)) return false
set.push(obj)
return true
}
}
What caught my eye was the snippet
~set.indexOf(obj)
It seems like this function is checking for the presence of obj
in the array set
. I always used set.indexOf(obj) == -1 in a case like this, but this got me to look it up.
The ~ operator is bitwise not, and you can read about it on MDN. Turns out ~x
evaluates to -x-1
so this will evaluate to a 0 when x = -1, and something non-zero otherwise!
Don't know if I'll use it, but the form does look nice!
💖 💪 🙅 🚩
Matthew Foley
Posted on May 31, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev Création de l'authentification pour l'utilisateur - Créer un blog avec Adonis
August 21, 2021
blockchain Comment créer un Asset ou Smart Asset en NodeJS sur la Blockchain Waves.
January 7, 2020