I'm a Java guy in a JavaScript world, and I'm used to certain things about Java Strings that just aren't there for in JavaScript. Some of this I can accept, for example Strings are freaking everywhere for some reason.
Now I realize this could be simply implemented with return this.indexOf(needle) === 0;
(or, even more JavaScripty, return this.indexOf(needle);
but the flaw in that is that it will search the entire (potentially somewhat lengthy, you never know) String in its endeavor to find the index, when I really only care if its non-zero.
My current solution, which passes my testing so far, is thus. I'm open to all feedback, but I'm most interested in
- Breaks from conventional JavaScript (the bad stuff, the smells)
- Corner-cases this fails for
- To a reasonable extent, style
I've also decided to tack it onto the class itself (I have to admit, I like being able to do that!) Is that bad practice?
String.prototype.startsWith = function(needle) {
// This was dubious, if only because most times "" gets passed
// it's by mistake... but decided since it was technically correct
// that it should stay
if(needle === "") return true;
// but in all other cases, falsey values were considered false
if(!needle) return false;
// our mission, to find the needle in the haystack - is this tacky?
var haystack = this;
// primarily here to prevent AIOOBEs in the loop - is this the most
// JavaScripty way to preempt that error?
if(needle.length > haystack.length) {
return false;
}
// I've read that 'i' is not scoped to this for loop, and that I would
// need let instead. I must support older browsers, is there a better
// way to do this?
for(var i = 0; i < needle.length; i++) {
if(haystack.charAt(i) !== needle.charAt(i)) {
return false;
}
}
return true;
}