Semantic Inference for Succinctness

While working on JavaScript++, it occurred to me the programs were becoming verbose a la Java. For example, to define a pure function, we might write:

pure function foo(int bar, int baz) {
    // ...
}

While JavaScript++ will infer whether or not a function is pure, I could not find it in my heart to do away with the “pure” keyword. Why? Because, in large-scale applications, it is important to be able to apply explicit restrictions. If it is desired for a function to be pure, we do not want a team member accidentally introducing side effects later on.

Continue reading Semantic Inference for Succinctness

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