Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.