radio/libjs/utils/enum.js

70 lines
2.1 KiB
JavaScript

"use strict";
var Class = require("./class");
var Enum = Class.inherit({
className: "Enum",
constructor: function(name, additional) {
if (typeof name !== "string" || name.length === 0) {
throw new Error("An attempt to register enum with wrong or empty name");
}
if (storage[name]) {
throw new Error("An attempt to register enum " + name + " for the second time");
}
Class.fn.constructor.call(this);
this.name = name;
this.straight = Object.create(null);
this.reversed = Object.create(null);
this.additional = Object.create(null);
this._additionals = additional || [];
this._lastId = 0;
storage[name] = this;
},
add: function(name, additional, id) {
if (typeof name !== "string" || name.length === 0) {
throw new Error("An attempt to add an entry with invalid name to enum " + name);
}
if (!id) {
id = this._lastId + 1;
}
if (this.straight[id] !== undefined) {
throw new Error("Id duplication in enum " + this.name + " during an attempt to add entry " + name);
}
if (this.reversed[name] !== undefined) {
throw new Error("Name duplication in enum " + this.name + " during an attempt to add entry " + name);
}
this.straight[name] = id;
this.reversed[id] = name;
this.additional[id] = Object.create(null);
for (var i = 0; i < this._additionals.length; ++i) {
var key = this._additionals[i];
var aVal = additional[key];
if (aVal === undefined) {
throw new Error("An attempt to add an entry " + name + " into enum " + this.name + " without providing additional value " + key);
}
this.additional[id][key] = aVal;
}
this._lastId = id;
},
hasAdditional: function(name) {
return this._additionals.indexOf(name) !== -1;
}
});
var storage = Object.create(null);
Enum.storage = storage;
module.exports = Enum;