Created
August 4, 2015 14:51
-
-
Save nathggns/213c44e306fdbde6444d to your computer and use it in GitHub Desktop.
Mini enum-like solution. Probably not all that useful;
This file contains hidden or 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
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]; | |
} | |
} |
This file contains hidden or 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
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