Skip to content

Instantly share code, notes, and snippets.

@tgoyer
Last active February 8, 2018 03:34
Show Gist options
  • Save tgoyer/0d8ce701fa0c10c46411f4883249fe2a to your computer and use it in GitHub Desktop.
Save tgoyer/0d8ce701fa0c10c46411f4883249fe2a to your computer and use it in GitHub Desktop.
Bitwise Flags Class with example
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