Juggling bits in JavaScript

(bitmasks)

What do we need

| - BITWISE OR

& - BITWISE AND

Bitmasks

How it works

Which flags are in the mask?

// FLAG A
var A = 1 // 001
// FLAG B
var B = 2 // 010
// MASK
var MASK = A | C // 101 {5}

// 001 OR
// 100
// ---
// 101 = 5{10}
// FLAG C
var C = 4 // 100
// FLAG A?

var inTheMask = MASK & A;

// 101 AND
// 001
// ---
// 001 = 1{10} Truthy!
// FLAG B?

var inTheMask = MASK & B;

// 101 AND
// 010
// ---
// 000 = 0{10} Falsy!
// FLAG C?

var inTheMask = MASK & C;

// 101 AND
// 100
// ---
// 100 = 4{10} Truthy!
function logger() {
	this.canSeeErrors = this.groups.ADMIN;
	this.canSeeDebugs = this.groups.SUPRUSER | this.groups.ADMIN;
	this.canSeeInfos = this.groups.USER | this.groups.SUPRUSER | this.groups.ADMIN;

}

logger.prototype.setUserGroup = function(level) {
	this.level = level;
}

logger.prototype.groups = {
	USER: 1, // 0001
	SUPRUSER:  2, // 0010
	ADMIN:  4, // 0100
}

logger.prototype.error = function(errorMessage) {
	if (this.canSeeErrors & this.level)
		console.log("%cERROR: " + errorMessage, "color: #FF033E; font-weight:bold;");
}

logger.prototype.debug = function(debugMessage) {
	if (this.canSeeDebugs & this.level)
		console.log("%cDEBUG: " + debugMessage, "color: #0000FF; font-weight:bold;");
}

logger.prototype.info = function(infoMessage) {
	if (this.canSeeInfos & this.level)
		console.log("%cINFO: " + infoMessage, "color: #C8A2C8; font-weight:bold;");
}

Book recomendation

Juggling with bits in JavaScript short

By Rinat U

Juggling with bits in JavaScript short

  • 318