Bitmasks in JavaScript

A lot of JavaScript developers will use objects as hash maps. They might take this further and set/unset flags and options for a function. For example:

[js]
function eat(foods) {
if (foods.chicken) { /* … */ }
if (foods.pork) { /* … */ }
if (foods.beef) { /* … */ }
}
[/js]

Unfortunately, objects in JavaScript are not necessarily “hash maps” (even if they’ve been implemented using hash maps). Objects are subject to the rules of prototypical inheritance. Therefore, in order to make the above code safe, we may need to add extra checks:

[js]
function eat(foods) {
if (Object.prototype.toString.call(food) !== "[object Object]") {
return false;
}

if (Object.prototype.hasOwnProperty.call(foods, chicken)) { /* … */ }
if (Object.prototype.hasOwnProperty.call(foods, pork)) { /* … */ }
if (Object.prototype.hasOwnProperty.call(foods, beef)) { /* … */ }
}
[/js]

Assuming you are writing safe code and not leaving things up to chance, you can see how this can quickly become messy.

In my previous blog post, I detailed the JavaScript Enum Pattern. We can combine enumerations with bitmasks to create flags that are faster, less memory-intensive, and easier to write. Due to the prevalence of objects, bitmasking is a technique more common in languages like C++, but they can actually be used in JavaScript.

Continue reading Bitmasks in JavaScript