Created
August 27, 2016 16:30
-
-
Save roboncode/32c1d31903e6135258fd3febec577154 to your computer and use it in GitHub Desktop.
Permissions using Binary
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
function Permissions() { | |
} | |
Permissions.createRules = function(options) { | |
var permissions = {}; | |
var num = 1; | |
var len = options.length; | |
for(var i=0;i<len;i++) { | |
if(i === 0) { | |
permissions[options[i]] = num; | |
} else { | |
num *= 2; | |
permissions[options[i]] = num; | |
} | |
} | |
return permissions; | |
} | |
Permissions.createPermissions = function (rules) { | |
var result = 0; | |
var len = rules.length; | |
for(var i=0;i<len;i++) { | |
result ^= rules[i]; | |
} | |
return result; | |
} | |
Permissions.checkPermission = function(permissions, rule) { | |
return Boolean(permissions & rule); | |
} | |
var rules = Permissions.createRules(['view', 'modify', 'create', 'delete']); | |
var permissions = Permissions.createPermissions([rules.modify, rules.delete]); | |
console.log('#view', Permissions.checkPermission(permissions, rules.view)); | |
console.log('#modify', Permissions.checkPermission(permissions, rules.modify)); | |
console.log('#create', Permissions.checkPermission(permissions, rules.create)); | |
console.log('#delete', Permissions.checkPermission(permissions, rules.delete)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment