Skip to content

Instantly share code, notes, and snippets.

@fabslab
Last active December 15, 2015 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabslab/5328123 to your computer and use it in GitHub Desktop.
Save fabslab/5328123 to your computer and use it in GitHub Desktop.
Higher-order messaging in JavaScript using Proxy
// 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