Skip to content

Instantly share code, notes, and snippets.

@justsml
Last active August 29, 2015 14:14
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 justsml/1a3d72778b189dd21d72 to your computer and use it in GitHub Desktop.
Save justsml/1a3d72778b189dd21d72 to your computer and use it in GitHub Desktop.
Functional BitWise Role Checking
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