Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@xiaods
Forked from stevekinney/method_missing.js
Created September 1, 2014 23:22
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 xiaods/eea2c189e49360651789 to your computer and use it in GitHub Desktop.
Save xiaods/eea2c189e49360651789 to your computer and use it in GitHub Desktop.
// This will only work in environments that support ES6 Proxies.
// As of right now, that's pretty much only Firefox.
function Refrigerator(foods) {
this.foods = foods;
return new Proxy(this, {
get: function (receiver, name) {
if (name in receiver) {
return receiver[name];
} else if (name.match(/^findBy(.+)$/)) {
return receiver.find.bind(receiver, name.match(/^findBy(.+)$/)[1].toLowerCase());
}
}
});
}
Refrigerator.prototype.find = function (attribute, query) {
return this.foods.filter(function (food) {
return food[attribute] === query;
});
};
var cucumber = { name: "cucumber", type: "veggie", tastiness: 5 };
var bacon = { name: "bacon", type: "meat", tastiness: 10 };
var celery = { name: "celery", type: "veggie", tastiness: 3 };
var fridge = new Refrigerator([cucumber, bacon, celery]);
console.assert(fridge.foods.length === 3, 'FAILED: Properties should pass through');
console.assert(!fridge.garbage, 'FAILED: Garbage properties should return undefined');
console.assert(fridge.find('name', 'cucumber')[0].name === 'cucumber', 'FAILED: Regular finder');
console.assert(fridge.findByName('cucumber')[0].name === 'cucumber', 'FAILED: Proxy finder');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment