Skip to content

Instantly share code, notes, and snippets.

@cdelaorden
Created June 25, 2015 15:59
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 cdelaorden/6e21cc5e4428267dd6ab to your computer and use it in GitHub Desktop.
Save cdelaorden/6e21cc5e4428267dd6ab to your computer and use it in GitHub Desktop.
ES2015 - Proxy - Dynamic properties (all*, any*) in Array
/**
* Proxy an Array - add all* property to filter by object predicate, and any* to emulate underscore some/any
*
* For example: proxy an array of objects, having some Boolean values on each of them
* following the is* predicate form. We'll then trap get calls, to return allXXX (sub array) or to
* query anyXXX (Boolean)
*
*/
let Users = new Proxy([
{ id: 1, username: 'Charlie', isAdmin: true, isRobot: false },
{ id: 2, username: 'Johnny-Five', isAdmin: false, isRobot: true },
{ id: 3, username: 'Sgt. Pepper', isAdmin: false, isRobot: false },
{ id: 4, username: 'Replicant', isAdmin: true, isRobot: true }
],
{
get(obj, prop){
if(prop.indexOf('all') === 0){
return this.getAll(obj, prop);
}
if(prop.indexOf('any') === 0){
return this.getAny(obj, prop);
}
return obj[prop];
},
getAll(obj, prop){
//find key with that name
let key = prop.replace('all', '');
//handle plural names
if(key.endsWith('s')){
key = key.substr(0, key.length-1);
}
return obj.filter(item => item['is' + key] === true);
},
getAny(obj,prop){
let key = prop.replace('any', '');
if(key.endsWith('s'))
key = key.substr(0, key.length-1);
return obj.filter(item => item['is' + key] === true).length > 0
}
});
console.log(Users.allRobot);
console.log(Users.anyAdmin);
console.log(Users.anyDrunk);
@cdelaorden
Copy link
Author

Only works in Firefox / MS Edge as of today

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment