4 ms·
You can stuff the logic of "who can do what" somewhere else. eg: var permissions = { "Superadmin": ["selfdestruct",...], "Admin": ["ban",...], "Ple
by chejazi 11y ago
You can stuff the logic of "who can do what" somewhere else. eg:
var permissions = {
"Superadmin": ["selfdestruct",...],
"Admin": ["ban",...],
"Plebe": ["post",...]
};
function roleCanDo(action, role) {
return permissions[role].indexOf(action) > -1;
}
Your check would look like:
if (roleCanDo("someaction", user.getRole()))
Sorry if JS isn't your thing.
- striking 11y agoSorry to nitpick, but indexOf is a bad idea. Using it is up to 1700x slower (worst case) than using object indices[1]. It's probably an O(n) operation, where indexing an Object is nearly always O(1). 1: https://jsperf.com/indexof-vs-object-lookup/4 https://jsperf.com/indexof-vs-object-lookup/4
- ar0b 11y agoJust poking around, could you explain why https://jsperf.com/indexof-vs-object-lookup/32 https://jsperf.com/indexof-vs-object-lookup/32 indexOf is the fastest in this revision?
- striking 11y agoThat revision tests the best case (looking for string "a") while the revision I picked tests the worst case (looking for string "xxx", which doesn't exist). I picked it just because it came up first in Google search. Testing in my browser (Safari 9.0.1, Mac OS X 10.10.5) still gives a 54x improvement to Object indexing, though. Perhaps getting the first value in an array is faster than indexing an Object in your browser. The point is, if the thing doesn't exist, this part of the program will be thousands of times slower, and will get slower as the list of roles grows. Meanwhile, the hash map will not.
- ar0b 11y agoThanks for the explanation!
- mosquito242 11y agoI'm not a hardcore JS dev, but it probably has to do with the speed of objects vs. arrays. In most languages, arrays are significantly faster (because they're basically one contiguous block of memory). [1] http://stackoverflow.com/questions/17295056/array-vs-object-efficiency-in-javascript http://stackoverflow.com/questions/17295056/array-vs-object-...