i got tired of manually assembling enums that didn't even work right in javascript and tried to figure out what properties i wanted out of enums and if javascript could give them to me. thankfully it could!
actual code: 190 characters
comments explaining the what and why of the code: 1240 characters
actual code: 190 characters
comments explaining the what and why of the code: 1240 characters
/* i REALLY wanted an enum form that
* 1. let me refer to things as `enumname.thing` and
* 2. loudly errored if i was using a name that wasn't actually in the enum.
* javascript will happily let you read undefined properties:
* var foo = {};
* var bar = foo.asdf;
* is entirely okay, and any error will only happen once you use bar for
* something. this was leading to any typos (or uses of outdated items) in my
* item enum generating errors, not where i made the typo, but deep in the guts
* of the item code, without any reference whatsoever to the typo. but
* javascript is a lot more strict about calling things that aren't functions;
* those will immediately error. hence: this.
*/
function Enum () {
// javascript closures are wild (b/c `i` is altered, it's equal to
// the-highest-enum-value-plus-one at the end of the loop, and consequently
// when we enter the closure by calling any of the enum functions, `i` is
// equal to its last values -- if we just went
// this[arguments[i]] = function () { return i; }
// that would always return the same number for every enum function. so we
// need to have an intermediate function to re-scope/maintain the value as it
// existed at the point the enum value was constructed.)
function scope (i) {
return function () {
return i;
}
}
for (var i = 0; i < arguments.length; i++) {
this[arguments[i]] = scope (i);
}
Object.freeze(this);
}