Last active
August 29, 2015 13:56
-
-
Save reergymerej/9284488 to your computer and use it in GitHub Desktop.
bitwise not vs. traditional 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
for (var i = 5; i >= -5; i--) { | |
console.log('~' + i + ' === ' | |
+ ~i + ' == ' + (~i ? true : false)); | |
} | |
// ~5 === -6 == true | |
// ~4 === -5 == true | |
// ~3 === -4 == true | |
// ~2 === -3 == true | |
// ~1 === -2 == true | |
// ~0 === -1 == true | |
// ~-1 === 0 == false | |
// ~-2 === 1 == true | |
// ~-3 === 2 == true | |
// ~-4 === 3 == true | |
// ~-5 === 4 == true | |
var str = 'teamwork'; | |
// the standard way | |
if (str.indexOf('i') > -1) { | |
console.log('i here'); | |
} | |
// the tricky way | |
if (~str.indexOf('i')) { | |
console.log('i here'); | |
} | |
console.log((str.indexOf('i') > -1) === true); | |
console.log((~str.indexOf('i')) === true); | |
console.log((str.indexOf('a') > -1) === true); | |
console.log((~str.indexOf('a')) === true); | |
// false | |
// false | |
// true | |
// false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment