Last active
December 15, 2015 21:49
-
-
Save fabslab/5328123 to your computer and use it in GitHub Desktop.
Higher-order messaging in JavaScript using Proxy
This file contains hidden or 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
// Inspired by this version for Ruby http://kbullock.ringworld.org/2007/03/26/higher-order-messaging/ | |
if (typeof Proxy != "undefined") { | |
try { | |
Array.prototype.where = new Proxy(Array.prototype.filter, { | |
apply: function(target, thisValue, args) { | |
return new Proxy({}, { | |
get: function(enumTarget, name) { | |
return function() { | |
var itemArgs = arguments; | |
return target.call(thisValue, function(item) { | |
return item[name].apply(item, itemArgs); | |
}); | |
} | |
} | |
}); | |
} | |
}); | |
// Example usage | |
String.prototype.longerThan = function(num) { | |
return this.length > num; | |
} | |
var arr = "Hello world this is Fabien".split(" "); | |
var result = arr.where().longerThan(4); | |
console.log(result); // ["Hello", "world", "Fabien"] | |
} catch (e) { | |
// Proxy object can exist but with a different form that is not constructible | |
// calling new Proxy() in this case will throw an error | |
console.log('Your environment does not support the new Proxies API.') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment