Interesting code snippet

I was looking into a function to allow me to sort an array of objects in JavaScript, and I stumbled upon this interesting little snippet:

    [-1, 1][+!!reverse]

When I first looked at this, I wasn’t quite sure what it did, but as I started to take it apart, it became clear. It’s a very clever little piece of code.

This was part of the return value of the sort function, which, if it returns a 1, sorts ASC, and -1 sorts DESC. This little snippet switches that.

The way it works, is it creates a small two-element array [-1, 1] and then pulls out the n-th element where n is +!!reverse.

It’s the same as writing:

    var test = [-1, 1];
    var idx = +!!reverse;
    return test[idx];

The !! part makes sure that reverse is a boolean, and the + converts it to an int.

Very interesting, and I had to look at it for a second to really figure it out.

Original snippet location:
http://stackoverflow.com/questions/979256/how-to-sort-an-array-of-javascript-objects#answer-979325

UPDATE: After playing with this code, and really looking at it, I’ve decided that this piece of code, while clever, is poor programming.

The reason I think this is for one, it’s not clear what it does at first glance, and secondly, it can be re-written to be both more readable, and less prone to errors.

I rewrote the code to look like this:

    (reverse ? -1 : 1)

The reason I did this was because when I tried to format the previous bit of code to fit my coding style, it broke. Apparently, the + needs to be directly connected to the variable that follows it to get the JavaScript quirk of changing that variable to an integer.

This small difference was enough for me to decide that this bit of code was too fragile and needed to go.

If you’ll also notice, in the original code, reverse was actually set when the sort order was normal (returning 1), and unset when the sort order was reversed (returning -1).  I also fixed this, making the name of the variable match it’s function, thereby making the code even more clear.