Svendtofte.com has a list of useful Javascript prototype methods inspired by functional programming. (Lovely)
But there’s one of his prototype methods that I have an opinion on, his string reverse method:
String.prototype.reverse = function() {
var s = "";
var i = this.length;
while (i>0) {
s += this.substring(i-1,i);
i--;
}
return s;
}
It’s a classic C style string reverse method. My suggestion is instead this:
String.prototype.reverse=function(){
return this.split("").reverse().join("");
}
What does it do?
x=”nitro2k01″.reverse() for example does this: this.split(“”) splits the string into an array, where every element is one character of the string. “nitro2k01″ in the example becomes the array ["n","i","t","r","o","2","k","0","1"]. .reverse() in turn reverses the array, so the new array becomes ["1","0","k","2","o","r","t","i","n"]. Lastly .join(“”) turns the new array back into a string, “10k2ortin”, which is returned.
I like my function better because it has a more functional look, re-uses builtin JS functionality and possily is faster. (Although I’ll have to investigate the last claim more thoroughly.)