Skip to content

Instantly share code, notes, and snippets.

@mediaupstream
Last active November 8, 2021 12:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mediaupstream/481ad35ca0fb0ddcf90f542bdb6205b1 to your computer and use it in GitHub Desktop.
Save mediaupstream/481ad35ca0fb0ddcf90f542bdb6205b1 to your computer and use it in GitHub Desktop.
Store CRUD settings in 2 bytes with bitmasks
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'
@mediaupstream
Copy link
Author

Store CRUD permissions in 2 bytes (16 bits) using bitwise operations.

@mediaupstream
Copy link
Author

mediaupstream commented Nov 10, 2017

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