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 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' |
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:
0x0000 -> no permissions
0x0001 -> create
0x0010 -> read
0x0011 -> create read
0x0100 -> update
0x0101 -> create update
0x0110 -> read update
0x0111 -> create read update
0x1000 -> delete
0x1001 -> create delete
0x1010 -> read delete
0x1011 -> create read delete
0x1100 -> update delete
0x1101 -> create update delete
0x1110 -> read update delete
0x1111 -> create read update delete
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Store CRUD permissions in 2 bytes (16 bits) using bitwise operations.