-
-
Save xiaods/eea2c189e49360651789 to your computer and use it in GitHub Desktop.
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
// 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