Last active
August 29, 2015 14:14
-
-
Save justsml/1a3d72778b189dd21d72 to your computer and use it in GitHub Desktop.
Functional BitWise Role Checking
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
var roles = {'admin': 8, 'user': 1, 'powerUser': 4 }, | |
user = {role: 12}; // 4 + 8 | |
function hasRoleName(chkRole) { | |
chkRole = typeof(chkRole) === 'string' ? [chkRole] : chkRole; | |
var roleSum = chkRole.reduce(function(last, curr, idx, list) { return last + (roles[list[idx]] || 0); }, 0); | |
return hasAnyRolesBit(roleSum); | |
} | |
function hasAllRolesBit(roleSum) { | |
return (roleSum & user.role) >= roleSum; // must match all bits! | |
} | |
function hasAnyRolesBit(roleSum) { | |
return (roleSum & user.role) > 0; // true if *any* flag matches | |
} | |
user = {role: 12}; | |
assert(hasRoleName('admin')); | |
assert(hasRoleName('powerUser')); | |
assert(!hasRoleName('user')); | |
// now try this user's role... | |
user = {role: 5}; | |
assert(!hasRoleName('admin')); | |
assert(hasRoleName('powerUser')); | |
assert(hasRoleName('user')); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment