Created
June 25, 2015 15:59
-
-
Save cdelaorden/6e21cc5e4428267dd6ab to your computer and use it in GitHub Desktop.
ES2015 - Proxy - Dynamic properties (all*, any*) in Array
This file contains hidden or 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
/** | |
* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Only works in Firefox / MS Edge as of today