Last active
February 8, 2018 03:34
-
-
Save tgoyer/0d8ce701fa0c10c46411f4883249fe2a to your computer and use it in GitHub Desktop.
Bitwise Flags Class with example
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
class Flag { | |
constructor() { | |
this.value = 0; | |
} | |
add(flag) { | |
this.value = this.value | flag; | |
} | |
remove(flag) { | |
this.value = this.value & ~flag; | |
} | |
has(flag) { | |
return !!(this.value & flag); | |
} | |
} | |
// Flag constants are powers of 2. | |
const POSITIONS = { | |
TOP: 1, | |
LEFT: 2, | |
BOTTOM: 4, | |
RIGHT: 8 | |
} | |
let myFlag = new Flag(); | |
myFlag.add(POSITIONS.TOP | POSITIONS.LEFT); | |
console.log(myFlag.value); | |
console.log("TOP: " + myFlag.has(POSITIONS.TOP)); | |
console.log("BOTTOM: " + myFlag.has(POSITIONS.BOTTOM)); | |
console.log("RIGHT: " + myFlag.has(POSITIONS.RIGHT)); | |
console.log("LEFT: " + myFlag.has(POSITIONS.LEFT)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment