public
Last active

Generic Array subclassing function using ECMA-Harmony Proxy features

  • Download Gist
es-harmony_array_subclassing.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
// 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;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.