Last active
December 12, 2015 01:58
-
-
Save vstarck/4695191 to your computer and use it in GitHub Desktop.
Inheriting from native Array using Proxies
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
var List = function() { | |
return new Proxy({ | |
constructor: List, | |
_array: [].slice.call(arguments), | |
size: function() { | |
return this._array.length; | |
}, | |
toString: function() { | |
return 'List[' + this._array.toString() + ']'; | |
} | |
}, { | |
get: function(target, name) { | |
if(name in target) { | |
return target[name]; | |
} | |
if(typeof target._array[name] == 'function') { | |
return function() { | |
var result = target._array[name].apply( | |
target._array, | |
arguments | |
); | |
return Array.isArray(result)? | |
List.apply(List, result): | |
result; | |
} | |
} | |
return target._array[name]; | |
}, | |
set: function(target, name, value, receiver) { | |
target._array[name] = value; | |
} | |
}); | |
}; | |
function assert(expr, msg) { | |
if(!expr) console.error(msg || 'FAIL!'); | |
} | |
var foo = new List(3,2,1) | |
assert(foo); | |
assert(foo.constructor == List); | |
assert(Array.isArray(foo._array)); | |
assert(typeof foo.forEach == 'function'); | |
assert(foo.length == foo.size()); | |
var mapped = foo.map(function(current) { | |
return current * current; | |
}); // [9, 4, 1] | |
assert(mapped); | |
assert(mapped.constructor == List); | |
assert(Array.isArray(mapped._array)); | |
assert(typeof mapped.forEach == 'function'); | |
assert(mapped.size() == foo.size()); | |
assert(foo.push(42) == 4) | |
assert(foo.size() == 4) | |
assert(mapped.toString() == "List[9,4,1]") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment