radio/libjs/utils/enum.js

70 lines
2.2 KiB
JavaScript
Raw Permalink Normal View History

"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 || [];
2018-10-28 21:32:44 +00:00
this._lastId = -1;
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;