Re:JS1k demo: “Highway at Night”
by tlrobinson on Sunday November 23, 2014 @01:38PM
(#8649466)
You definitely should learn bitwise operators, but if other people have to work with your code I'm not generally in favor of applying them in clever ways where there's a slightly more verbose but much more readable solution (e.x. "~x.indexOf(y)" vs "x.indexOf(y) !== 0"... just type the extra 3 characters)
[ Parent
| on HN ]
As a rule of thumb, when ever one thinks that "wow, this code I just wrote is really clever", it should be a sign to sit back, take another approach and rewrite that code.
Clever code almost always means that in hindsight it's terrible and will introduce bugs.
In my opinion "x.indexOf(y) !== 0" is a lot more clearer and will immediately tells other developers what is happening. No point in saving space code, that's why we have minification libraries.
Nobody needs this correction, I hope, but to be clear, it's !== -1 that we're replacing with ~. Then again, maybe this stands as a valid reason to be explicit in the first place. ;-)
A perfect example of why "~x.indexOf(y)" may actually be better... you just messed up, as the alternative should be "x.indexOf(y) !== -1" or "x.indexOf(y) >= 0" or "x.indexOf(y)+1" ...
In any case, it's all a matter of style... because if you don't know that indexOf will return 0 for a positive match, you will still mess up.