Last active
August 29, 2015 14:07
-
-
Save mathieumg/8ea6cb70ae161135a28a to your computer and use it in GitHub Desktop.
Enum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//FIXME: This is not released yet. https://github.com/mdevils/node-jscs/pull/548 | |
/* jscs: disable disallowDanglingUnderscores */ | |
/** | |
* A module representing the Enum data type. | |
* @module utilities/types/Enum | |
*/ | |
"use strict"; | |
var _ = require("lodash"), | |
FunctionCallError = require("../errors").FunctionCallError, | |
MissingParameterError = FunctionCallError.MissingParameterError, | |
InvalidParameterError = FunctionCallError.InvalidParameterError; | |
/** | |
* Enumeration of values. Often used to describle possible values of a state | |
* variable. | |
* @param {Array} values Array of Strings that will be assigned a value in | |
* order. (Starting at 0) | |
*/ | |
function Enum(values) { | |
if (_.isUndefined(values)) { | |
throw new MissingParameterError( | |
null, | |
"You need to instanciate Enum with an Array of Strings." | |
); | |
} | |
if (!_.isArray(values)) { | |
throw new InvalidParameterError( | |
null, | |
"You need to instanciate Enum with an Array of Strings.", | |
values | |
); | |
} | |
var self = this; | |
this._values = values; | |
this.length = this._values.length; | |
_.forEach(this._values, function (value, index) { | |
self[value] = index; | |
}); | |
Object.freeze(this); | |
} | |
/** | |
* Returns the maximum possible value for the Enum. | |
* @return {Number} Biggest value in the Enum. (Last one) | |
*/ | |
Enum.prototype.getMax = function () { | |
return this.length - 1; | |
}; | |
/** | |
* Returns the original Array provided to create the Enum. | |
* @return {Array} Array of Strings initially provided to the constructor. | |
*/ | |
Enum.prototype.getList = function () { | |
return this._values; | |
}; | |
/** | |
* Returns mapping of the Enum keys with their associated numerical value. | |
* @return {Object} Object literal with the Enum values mapping. | |
*/ | |
Enum.prototype.getValues = function () { | |
var self = this; | |
return this._values.map(function (value) { | |
return self[value]; | |
}); | |
}; | |
/* jscs: enable */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment