Wednesday, October 23, 2013

EMCA Sub Arrays - An Interesting Technique

Dealing with javascript arrays can be a breeze, or it can be bothersome. The array.length property having the ability to change the array is VERY difficult to replicate. You almost cannot make your own typed arrays. At least you can get pretty close. Take the following code snippet I am investigating.

Running this code will make a ZOMBIE array (as I call it.)

(Warning, I am not responsible for unintended "features" your code exhibits.)

function SubArray(length){
   Array.call(this); //"Magic"
   if(typeof length == "number" && length%1==0&&arguments.length==1){
     this.length = length; //Length has to be set manually for some reason.
   }
   else{
     var _len = arguments.length;
     this.length = _len;
     for(var i = 0; i<_len; i++)
        this[i] = arguments[i];
   }
}

SubArray.prototype = [];

var x = new SubArray();

Presto Change-o!

Suddenly you have a strongly typed array, albeit with a few small caveats.

//Evaluate the following
var x = new SubArray();

typeof x; //"object" -- Just like when you declare a new Array....
Object.prototype.toString.call(x); //"[object Object]" -- To be expected
x instanceof Array;//true -- This is the way the Array functionality would be identified

x.push(1); //2
x;//[undefined, 1]
x[2] = "test";

//Drum roll please....
x;//[undefined, 1]

Wait... what? The property wasn't even set! It just disappeared. Or did it? Check console.log(x[2]); . So what really happened is the .length property wasn't set and the array wasn't updated. However, if this particular limitation does not hold you back, it's very easy to work with it because you haven't done ANYTHING to modify a native prototype.

I would probably use this technique for some fun stuff, but what you really wanted was an Array in the first place... so just return an array and add some properties to it instead. It's lame, but it works.

Or you could simply wait for Native Object inheritance in some later version of EMCAscript that is coming down the pipeline.

In functional health, Josh

No comments:

Post a Comment