Last active
November 8, 2021 12:34
-
-
Save mediaupstream/481ad35ca0fb0ddcf90f542bdb6205b1 to your computer and use it in GitHub Desktop.
Store CRUD settings in 2 bytes with bitmasks
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
| const CREATE = 0 | |
| const READ = 1 | |
| const UPDATE = 2 | |
| const DELETE = 3 | |
| const add = (a, b) => a |= (1 << b) | |
| const remove = (a, b) => a &= ~(1 << b) | |
| const has = (a, b) => ((a & (1 << b)) > 0) | |
| const bin = (a) => (s).toString(2) | |
| // --- example usage | |
| let s = 0 | |
| s = add(s, CREATE) // 1 | |
| s = add(s, READ) // 3 | |
| s = add(s, UPDATE) // 7 | |
| has(s, CREATE) // true | |
| has(s, DELETE) // false | |
| s = remove(s, CREATE) // 6 | |
| has(s, CREATE) // false | |
| s // 6 | |
| bin(s) // '110' |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
because there are 16 possible combinations of CRUD (4*4) and there are 8 bits per byte we can store all the information in 16 bits.
All possible permissions, which looks like: