Enumerables in JavaScript
Creating clean, readable code is a primary imperative when working with large systems. Today, I have factored the knockout view model from a single object for both projects into an inheritance based hierarchy. Now in the middle of it, I’m replacing a programmingLanguage variable with a language class that also handles the language for the style sheet (LESS, SCSS) and document (Jade, ECO).
var Language = Class.$extend({
__init__: function () {
LANGUAGE = {
PYTHON: 0,
JAVASCRIPT: 1,
LESS: 2,
CSS: 3,
HTML: 4
};
LANGUAGE_TYPE = {
STYLE: 1,
}
}
})
__init__: function () {
LANGUAGE = {
PYTHON: 0,
JAVASCRIPT: 1,
LESS: 2,
CSS: 3,
HTML: 4
};
LANGUAGE_TYPE = {
STYLE: 1,
}
}
})
Then I paused and thought it didn’t seem right. I remember Enums were more terse in C. So I decided to us an Enum class.
function Enum() {
var obj = new Object();
for (var i = 0; i < arguments.length; i++) {
obj[arguments[i]] = i;
}
return obj;
}
var Language = Class.$extend({
__init__: function () {
LANGUAGE = Enum('PYTHON', 'JAVASCRIPT', 'LESS', 'CSS', 'HTML');
LANGUAGE_TYPE = Enum('SCRIPT', 'STYLE', 'DOCUMENT');
}
})
var obj = new Object();
for (var i = 0; i < arguments.length; i++) {
obj[arguments[i]] = i;
}
return obj;
}
var Language = Class.$extend({
__init__: function () {
LANGUAGE = Enum('PYTHON', 'JAVASCRIPT', 'LESS', 'CSS', 'HTML');
LANGUAGE_TYPE = Enum('SCRIPT', 'STYLE', 'DOCUMENT');
}
})
Now I like that much better. It’s like automatic numbering, except I don’t have to read it.