Day 13 of the 30 Day Writing Challenge
The idea for this post all started with a friend of mine, Connor McSheffrey (@mcsheffrey). I don’t normally see a whole lot of activity from Connor on github. This morning, he posted a short gist:
I took a look at noticed something I didn’t understand. The ~~ operator. So, I had to start researching. For whatever reason, Google doesn’t recognize ~~ in the search engine. I tried surrounding it with quotes etc and nothing relavent came up (please let me know why)! I knew this was an operator, so I started searching for operators. Sure enough, I found the ~ operator. I didn’t even know this one existed. Do you know what this does? Let’s break it down:
The ~ operator takes an integer, inverts the value, and subtracts 1 from it. In our case, 8 becomes -8, and -8 + -1 === -9. A “nice to know” but this didn’t answer my question. I continued my search, this time for “bitwise operators”. After buttload of searching, I found this awesome JS Perf presentation by Thomas Fuchs.
Back to the Thomas Fuchs slide share. He brings up this operation:
and the faster:
Side note: Thomas doesn’t need the whole 1 * “12.5”, it can just be “12.5”
Now we have a name for our operator: the bitwise Double Not (~~).
Before we get back to Connor’s script, let’s break down the Double Not. Here’s a couple of examples:
1 2 3
There is one more thing the Double Not does for us.
Damn you James Padolsey for being so smart. He blogged about the Double Not over a year ago and added this little nugget:
” ~~‘s flooring capabilities make it a better alternative to Math.floor if you know you’re dealing with positives — it’s faster and takes up less characters. ”
So, it’s a micro perf for Math.floor (in some browsers)! Nice nugs dude!
I’m hoping this is looking a little familiar. 0’s and 1’s, falsy and truthy… ahhh!!!
1 2 3
Back to Connor’s gist:
Depending on the string match of “next” we get a boolean value cough carousel nav cough AND we will +1 to
this.current or -1 from
this.current. It works perfectly with going to the next picture, or the previous picture in a photo carousel.
These sites were exremely valuable when researching Connor’s jizzst!
James Padolsey’s Double bitwise NOT (~~)
MDN’s Old BitWise Operators Page - cached version, original is a dead link
tuts+ - Where Connor originally saw this
…another fun thing this research has taught me, typing ~~ and another ~~ in octopress is the same as using
<del></del> tags. Yay.
Special thanks to Connor for posting a single, simple gist that got me going on this whole subj. Kisses!!!