Created
September 20, 2013 18:07
-
-
Save jsdevel/6641430 to your computer and use it in GitHub Desktop.
bit masking fun with javascript.
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
/** | |
* A map of bit masks that correlate to a person's status. | |
* @type {Object} | |
*/ | |
var personStatus=(function(){ | |
var i=0.5; | |
return { | |
CODING:(i*=2), | |
EATING:(i*=2), | |
READING:(i*=2), | |
SLEEPING:(i*=2), | |
WORKING:(i*=2) | |
}; | |
})(); | |
/** | |
* A State object that uses bit flags to maintain state. | |
* @constructor | |
*/ | |
function State(){ | |
this._state=0; | |
} | |
/** | |
* @param {number} | |
*/ | |
State.prototype.is=function(number){ | |
if(number < 1){ | |
return false; | |
} | |
return !!(this._state&number); | |
}; | |
State.prototype.set=function(number){ | |
this._state=this._state|number; | |
}; | |
var joeState=new State; | |
joeState.is(personStatus.CODING);//false | |
joeState.set(personStatus.CODING); | |
joeState.is(personStatus.CODING);//true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment