Skip to content

Instantly share code, notes, and snippets.

@marlun78
Last active August 29, 2015 14:06
Show Gist options
  • Save marlun78/bc61c76f3269738f3ff8 to your computer and use it in GitHub Desktop.
Save marlun78/bc61c76f3269738f3ff8 to your computer and use it in GitHub Desktop.
Provides an immutable enum type
/**
* Enum.js
* Provides an immutable Enum type
* Copyright (c) 2014 marlun78
* MIT License, https://gist.github.com/marlun78/bd0800cf5e8053ba9f83
*
* @example:
* var colors = new Enum({
* RED: '#f00',
* GREEN: '#0f0',
* BLUE: '#00f'
* });
*
* colors.RED; // #f00
*
* colors.getValueByKey('RED'); // #f00
* colors.getValueByKey('dog'); // undefined
*
* colors.hasValue('#00f'); // true
* colors.hasValue('dog'); // false
*
* colors.getKeyByValue('#f00'); // 'RED'
* colors.getKeyByValue('dog'); // undefined
*
* colors.hasKey('BLUE'); // true
* colors.hasKey('dog'); // false
*
* colors.dog = 'pudel'; // 'pudel'
* colors.hasKey('dog'); // false
* colors.dog; // undefined
*/
var Enum = (function () {
'use strict';
/**
* Immutable Enum Type
* @typedef {Object} Enum
* @property {Function} getKeys
* @property {Function} getValues
* @property {Function} hasKeys
* @property {Function} hasValues
*/
/**
* @constructor
* @param {object} map
* @returns {enum}
*/
function Enum(map) {
// Copy properties from host map
for (var key in map) {
if (map.hasOwnProperty(key)) this[key] = map[key];
}
// Make immutable
Object.freeze(this);
}
Enum.prototype = {
constructor: Enum,
/**
* Retrieves the key for a value
* @param {*} value - The value of the key to get
* @returns {string|undefined}
*/
getKeyByValue: function getKeyByValue(value) {
for (var key in this) {
if (this.hasOwnProperty(key) && this[key] === value) return key;
}
},
/**
* Retrieves the value for a key
* @param {string} key - The key of the value to get
* @returns {*}
*/
getValueByKey: function getValueByKey(key) {
if (this.hasOwnProperty(key)) return this[key];
},
/**
* Checks if the passed key exists or not
* @param {string} key - The key of the value to get
* @returns {Boolean}
*/
hasKey: function hasKey(key) {
return this.hasOwnProperty(key);
},
/**
* Checks if the passed value exists or not
* @param {*} value - The value of the key to get
* @returns {boolean}
*/
hasValue: function hasValue(value) {
for (var key in this) {
if (this.hasOwnProperty(key) && this[key] === value) return true;
}
return false;
}
};
return Enum;
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment