Skip to content

Instantly share code, notes, and snippets.

@corymartin
Created April 15, 2012 14:55
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save corymartin/2393268 to your computer and use it in GitHub Desktop.
Save corymartin/2393268 to your computer and use it in GitHub Desktop.
Flag Enumerations in JavaScript
// Flag Enumerations in JavaScript
// ===============================
// Flag enums
// ----------
// Values must increment by powers of 2
var SEASONS = {
Spring : 1,
Summer : 2,
Fall : 4,
Winter : 8
};
var DAYS = {
None : 0x0, // 0 *
Sunday : 0x1, // 1
Monday : 0x2, // 2
Tuesday : 0x4, // 4
Wednesday : 0x8, // 8
Thursday : 0x10, // 16
Friday : 0x20, // 32
Saturday : 0x40 // 64
};
// * Cannot use 0 in a bitwise `&` operation to test for a flag b/c it will
// always result in zero. However, it can be used for logical comparisons.
// Usage examples (contrived)
// --------------------------
var getSeasonsSelected = function( seasons ) {
var selected = [];
// The perens are needed around the bitwise operation due to the
// greater operator precedence of `===`
if ( (seasons & SEASONS.Spring) === SEASONS.Spring ) selected.push('Spring');
if ( (seasons & SEASONS.Summer) === SEASONS.Summer ) selected.push('Summer');
if ( (seasons & SEASONS.Fall) === SEASONS.Fall ) selected.push('Fall');
if ( (seasons & SEASONS.Winter) === SEASONS.Winter ) selected.push('Winter');
return selected;
};
var s1 = getSeasonsSelected( SEASONS.Spring | SEASONS.Fall );
console.log(s1);
//=> ["Spring", "Fall"]
// ----------------
var getDaysSelected = function( days ) {
if (days === DAYS.None) return [];
var selected = [];
for (var flag in DAYS) {
if (flag === 'None') continue;
var val = DAYS[flag];
if ( (days & val) === val ) selected.push(flag);
}
return selected;
}
var myDays = DAYS.Monday | DAYS.Friday;
myDays |= DAYS.Wednesday;
var d1 = getDaysSelected( DAYS.Monday | DAYS.Sunday | DAYS.Monday | myDays | DAYS.Monday );
console.log(d1);
//=> ["Sunday", "Monday", "Wednesday", "Friday"]
var d2 = getDaysSelected( DAYS.None );
console.log(d2);
//=> []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment