Created
November 25, 2013 12:40
-
-
Save paulosborne/7640679 to your computer and use it in GitHub Desktop.
Hipster indexOf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var message = "hello, how are you Tal?"; | |
if (~message.indexOf('Tal')) { | |
console.log('found matching text'); | |
} |
Since I don't feel this has really been explained--~
is the bitwise NOT operator in JS. ~-1
is 0, and ~anythingBesidesNegativeOne
is something other than 0. 0 is falsey, and all other numbers are truthy. Therefore, in those very few cases where -1
really means false
, you can use the tilde operator to turn -1 into 0, and any other number into something besides 0.
I wouldn't advise using this technique, though, at least not with code that many others will need to understand, maintain or enhance. It's quite obscure and a quick-and-dirty test (in Node) suggests that the difference in performance between using ~x
vs 'x > -1` is so small as to be nonexistent.
function tilde(count) {
console.time('tilde');
for (var i = 0; i < count; i++) ~i;
console.timeEnd('tilde');
}
function greaterThanNegativeOne(count) {
console.time('greaterThanNegativeOne');
for (var i = 0; i < count; i++) i > -1;
console.timeEnd('greaterThanNegativeOne');
}
var count = process.argv[2];
tilde(count);
greaterThanNegativeOne(count);
Results
$ node tildeVsGreaterThan.js 100000000
tilde: 8437ms
greaterThanNegativeOne: 8438ms
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nope