Created
January 20, 2012 16:27
-
-
Save paulmillr/1648257 to your computer and use it in GitHub Desktop.
ECMAScript 6 proxies fun (method missing, negative array indexes)
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
# Ruby’s “method missing” analog with ES6 proxies. | |
proxify = (object) -> | |
new Proxy object, get: (receiver, name) -> | |
object[name] ? object.methodMissing.bind object, name | |
object = proxify | |
a: 1, | |
b: 15, | |
c: -> | |
'called' | |
methodMissing: (name, args...) -> | |
console.log "Calling missing method #{name} with arguments", args | |
console.log 'Accessing property "a":', object.a | |
console.log 'Accessing property "b":', object.b | |
console.log 'Calling method "c":', object.c() | |
object.methodName 1, 2, 3, 4 |
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
# Negative array indexes with ES6 direct proxies. | |
enableNegativeIndexes = (array) -> | |
new Proxy array, get: (receiver, name) -> | |
console.log 'Proxy#get', array, name | |
index = parseInt name | |
if not isNaN(index) and index < 0 | |
array[array.length + index] | |
else | |
array[name] | |
# array = enableNegativeIndexes [100, 500, 600] | |
# array[-1] is 600 | |
# => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
yes and it doesn't work with nodejs since that uses v8 :(