Skip to content

Instantly share code, notes, and snippets.

@nathggns
Created August 4, 2015 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nathggns/213c44e306fdbde6444d to your computer and use it in GitHub Desktop.
Save nathggns/213c44e306fdbde6444d to your computer and use it in GitHub Desktop.
Mini enum-like solution. Probably not all that useful;
import { invert, assign, object } from 'lodash';
class Enum {
// Should probably look into using a Symbol for this instead??
static privateKey = '_private';
constructor(map) {
const inverted = invert(map);
const keys = Object.keys(map);
this[Enum.privateKey] = { map, inverted, keys };
assign(this, object(keys.map((k, i) => [k, i + 1])));
}
getForIndex(idx) {
return this.getPrivate().keys[idx - 1];
}
isValidKey(index) {
return typeof this.getForIndex(index) !== 'undefined';
}
value(index) {
return this.getPrivate().map[this.getForIndex(index)];
}
getPrivate() {
return this[Enum.privateKey];
}
}
const enum = new Enum({ OPT_ONE : 'one', OPT_TWO : 'two', OPT_THREE : 'three' });
enum.isValidKey(enum.OPT_ONE); // true
enum.value(enum.OPT_ONE); // 'one'
enum.isValidKey(enum.foo); // false
enum.value(enum.foo); // undefined
enum.OPT_ONE; // 1
enum.OPT_TWO; // 2
enum.OPT_THREE; // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment