Archive for the 'javascript' Category

String reverse prototype function in Javascript

December 27, 2007

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.)

Numeric array sort in Javascript

July 3, 2006

(This is a response to Hakan Bilgin’s post Javascript Array: Sorting on his blog challenger)

Hakan presents a function for sorting a javascript array numerically, as opposed to alphabetically ([1,2,3,21].sort() => [1,2,21,3]) Such functions have existed about as long as people have needed to sort javascript arrays. However hakan’s function introduces two new features, namely the ability to choose sort order, (Which btw is defaulted to descending order in his function) and that it takes care of non-numerical objects, such as strings, in the array, and puts them in the higher end of the sorted array.

One thing I don’t like about his implementation is that it doesn’t work well with decimal numbers. ([1,2.4,2].sort_int(1) => [1,2.4,2]) 2.4 is simply rounded to 2 by parseInt and will not be guaranteed to end up on the right side of 2. But of course, sort_int was not meant to be used this way.

Anyway, I propose this code to the job:

Array.prototype.numsort=function(d){
    var d = d || -1;

    return this.sort(function(a,b){
        if (isNaN(a-b))
            return (isNaN(a)?1:-1)*d;

    return (a-b)*d;
    });
}

// Test the code
alert([1, 12, "a", 3, 29, 34, 4, 4.5, 4, 6, 46].
    numsort(-1));

I guess that’s it. If there’s anything fundamentally wrong with this code, please let me know. :)