Created
August 18, 2010 08:10
-
-
Save cms/533954 to your computer and use it in GitHub Desktop.
Generic Array subclassing function using ECMA-Harmony Proxy features
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Generic function to subclass an array in JavaScript | |
// (using the ECMAScript Harmony Proxy features) | |
// Structuring of code inspired by @kangax's | |
// array_subclassing (http://github.com/kangax/array_subclassing) | |
var makeSubArray = (function () { | |
var MAX_UINT32 = Math.pow(2, 32) - 1; | |
return function (properties) { | |
properties || (properties = {}); | |
properties.length = { value: 0, writable: true }; | |
var obj = Object.create(Array.prototype, properties); | |
function enumerate() { | |
return Object.keys(obj); | |
} | |
var handler = { | |
get: function (receiver, name) { | |
return obj[name]; | |
}, | |
set: function (receiver, name, value) { | |
var len, index = name >>> 0; // ToUint32 | |
if (index === +name && index < MAX_UINT32){ | |
len = index + 1; | |
obj.length = Math.max(len, obj.length); | |
} else if (name == 'length'){ | |
len = value >>> 0; // ToUint32 | |
if (len !== +value) { | |
throw new RangeError(); | |
} | |
for (var i = len; i < obj.length; i++) { | |
delete obj[i]; | |
} | |
value = len; | |
} | |
obj[name] = value; | |
}, | |
hasOwn: function(name) { | |
return Object.prototype.hasOwnProperty.call(obj, name); | |
}, | |
has: function(name) { | |
return name in obj; | |
}, | |
enumerate: enumerate, | |
enumerateOwn: enumerate, // enumerateOwn presumably will be renamed to keys | |
getOwnPropertyNames: function () { return Object.getOwnPropertyNames(obj); }, | |
getOwnPropertyDescriptor: function () { return Object.getOwnPropertyDescriptor(obj); } | |
}; | |
return Proxy.create(handler, Array.prototype); | |
}; | |
})(); | |
function SubArray(n) { | |
var arr = makeSubArray(); | |
if (arguments.length == 1 && typeof n == 'number') { | |
arr.length = arguments[0]; | |
} else { | |
arr.push.apply(arr, arguments); | |
} | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment