Last active
August 29, 2015 14:25
-
-
Save ulfryk/0bbbd6f0cd0d4dd78952 to your computer and use it in GitHub Desktop.
TypeScript like JavaScript enumerators
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
var Enum = (function () { | |
function Enum() { | |
var args; | |
if (!(this instanceof Enum)) { | |
throw Error('Always use Enum constructor with new keyword.'); | |
} | |
args = this.getArgs(arguments); | |
if (args.some(function (arg) { return typeof arg !== 'string'; })) { | |
throw TypeError('All Enum arguments have to be strings.'); | |
} | |
args.forEach(this.setValue, this); | |
this.initialArgs = args; | |
Object.freeze(this); | |
} | |
Enum.indexingBase = 1; | |
Enum.prototype.setValue = function (arg, index) { | |
this[this[arg] = index + Enum.indexingBase] = arg; | |
}; | |
Enum.prototype.getArgs = function (argumentsPseudoArray) { | |
return Array.prototype.map.call(argumentsPseudoArray, function (arg) { | |
return arg; | |
}); | |
}; | |
Enum.prototype.toString = function () { | |
return 'Enum { ' + this.initialArgs.join(', ') + ' }'; | |
}; | |
return Enum; | |
}()); |
Author
ulfryk
commented
Jul 27, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment