Created
August 14, 2020 18:09
-
-
Save prof3ssorSt3v3/ac03e6db33bf5d71a646320605b20e8c to your computer and use it in GitHub Desktop.
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
/** | |
* Using a single integer to represent multiple permissions | |
* based on binary values using bitwise operators | |
* | |
* & bitwise AND - if both the top and bottom bit are 1, result is 1 | |
* | bitwise OR - if either the top and bottom bit or both are 1, result is 1 | |
* ^ bitwise XOR - if only one of the bits are 1, result is 1 | |
* 0101 | |
* 0100 & = 0100 | |
* | |
* 0100 | |
* 1110 | = 1110 | |
* | |
* 0101 | |
* 0001 ^ = 0100 | |
* | |
* 0 - 0000 | |
* 1 - 0001 x | |
* 2 - 0010 x | |
* 3 - 0011 | |
* 4 - 0100 x | |
* 5 - 0101 | |
* 6 - 0110 | |
* 7 - 0111 | |
* 8 - 1000 x | |
* 9 - 1001 | |
* 10 - 1010 | |
*/ | |
const READ = 1; // 0001 | |
const DRINK = 2; // 0010 | |
const SING = 4; // 0100 | |
const DELETE = 8; // 1000 | |
class Person { | |
constructor(name, access = 0) { | |
this.name = name; | |
this.access = access; | |
} | |
getAll() { | |
return { | |
[READ]: !!(this.access & READ), | |
[DRINK]: !!(this.access & DRINK), | |
[SING]: !!(this.access & SING), | |
[DELETE]: !!(this.access & DELETE), | |
}; | |
} | |
addPerm(perm) { | |
this.access = this.access | perm; | |
} | |
removePerm(perm) { | |
if (this.getAll()[perm]) { | |
this.access = this.access ^ perm; | |
} | |
} | |
} | |
let steve = new Person('Steve', 5); | |
let joanne = new Person('Joanne'); | |
joanne.addPerm(DRINK); | |
joanne.addPerm(SING); | |
joanne.addPerm(DELETE); | |
steve.addPerm(SING); | |
joanne.removePerm(READ); | |
steve.removePerm(READ); | |
console.log(steve.access, steve.getAll()); | |
console.log(joanne.access, joanne.getAll()); | |
// console.log(steve.getAll()[READ]); | |
// console.log(joanne.getAll()[READ]); |
Both work equally well.
The first is casting the number to a Boolean. The second casts to Boolean and flips it twice. So, in theory the first one may save you a fraction of a millisecond.
But the second one is quicker to type when I code. :)
Both work equally well.
The first is casting the number to a Boolean. The second casts to Boolean and flips it twice. So, in theory the first one may save you a fraction of a millisecond.
But the second one is quicker to type when I code. :)
Great, thank you!
Please ask any future questions in the comments on YouTube so everyone can see the answer.
Great explanation. Thanks for sharing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello Steve! Great lesson as always. I've seen that
Boolean(this.access & READ)
seems to work as well as!!(this.access & READ)
. Would you recommend one over the other? Thank you!