Saturday, May 5, 2012

JavaScript Fun Part 6: Code Golf, JavaScript Shorthand And Stupid JS Tricks!

JavaScript Is Often Code Golf

Because JavaScript is generally used on the browser, and the size of your JavaScript frequently effects load times of web pages, JavaScript code offers a fun, unique and practical opportunity to play "Code Golf" where other, compiled languages do not. What I mean by "Code Golf" is simply, trying to get code down to the fewest number of characters possible. Just like the one with the fewest strokes in golf is the winner.

Code Golf Fibonacci

Refactoring your code to make it less intensive to send over the wire can involve a bit more than simple minification. Refactoring your code to make it "smaller" is a fun task, but it commonly results in harder to read code. Here are a few examples of the classic Fibonacci sequence method where I'm using quite a bit of JavaScript shorthand to reduce the number of characters in my code.

First the plain example

// 167 characters. Not the best.
var a = 0;
var b = 0;
var next;
for (var i = 0; i < 10; i++) {
    if (b == 0) {
        b = 1;
    }
    console.log(b);
    next = a + b;
    a = b;
    b = next;
}​

Now for code golf!

//74 characters!​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
var r=[];for(var i=0;i<10;i++){console.log(r[i]=(r[i-1]||1)+(r[i-2]||0));}
//67 characters
var i=0,p=0,c=0,n;while(i++<10){console.log(((n=p+c||1,p=c),c=n));}
//Old winner: 64 characters
for(var n=1,i=0,p=0,c=1;i<10;n=p+c,p=c,c=n,i++){console.log(n);}
//New winner: 51 characters (still keeping the var, so + or - 4 chars):
for(var i=0,p=0,c=1;i<10 data-blogger-escaped-c="p+c),i++);" data-blogger-escaped-console.log="" data-blogger-escaped-p="" data-blogger-escaped-pre="">


JavaScript Shorthand

JavaScript actually has a number of shorthand methods for doing common (and uncommon) tasks that can help immensely when you are trying to limit the number of characters in what your doing.
var o = {}       //object literal
var a = []       //new array
var r = /.*/     //new regex
var s = ''+0;    //convert to string
var n = +'7';    //convert to number (7)
var b = !!'';    //converts to a boolean
var f = ~~3.434; //same as Math.floor(3.434)
var g = -~3.434; //same as Math.ceil(3.434)
var x = 5e3;     //same as 5000
var c = c || z;  //coalesce, if c is null then set it to z.
'abcde'[1];      //charAt shorthand, results in 'b'.
+new Date();     //shorthand for (new Date()).getTime();
var a = x?y:z;   //ternary operator, short for: var a;if(x){a=y;}else{a=z;}
!0               //shorthand for true (actually boolean)
!1               //shorthand for false (also boolean)
if(x){}          //if x is not false, null, undefined, '' or 0.

Weird JavaScript "Encoded" Strings!

alert((''+{}._)[5]+' '+(''+{}.$)[0]+(''+!0)[1]+(''+{}._)[5]+(''+{}[$])[6]+(''+!1)[1]+(''+{})[6]+(''+!0)[3]+(''+{}.$)[2]);

So what's going on here?

What this is doing is leveraging the shorthand above for silly purposes. You'll notice, when you break it down, what it's doing is concatinating a bunch of string fragments together that where retreived by converting things like [object Object] and "undefined" to strings with the ''+ conversion technique. The fragments were retrieved by index with the "abc"[0] technique mentioned above. It's pure silliness, obviously, but it's a good example of how crazy you can get with these shorthand techniques. Even if, in this case, the shorthand techniques aren't shorting anything, they're just meant to make the code look confusing.

No comments:

Post a Comment

This form allows some basic HTML. It will only create links if you wrap the URL in an anchor tag (Sorry, it's the Blogger default)