Skip to content

Instantly share code, notes, and snippets.

@stickupkid
Created September 6, 2012 18:08
Show Gist options
  • Save stickupkid/3659057 to your computer and use it in GitHub Desktop.
Save stickupkid/3659057 to your computer and use it in GitHub Desktop.
Enum
var scope = this;
function _Enum(ns, value, types, values){
this.ns = ns;
this.value = value;
this.types = types;
this.values = values;
function validate(){
var total = types.length;
if(total != values.length)
throw new Error("Lengths do not match");
else {
for(var i = 0; i < total; i++){
var value = values[i];
var type = types[i];
if(typeof value === "number" && type == Number){
continue;
} else if(typeof value === "string" && type == String){
continue;
} else if(typeof value == "object" && value instanceof type){
continue;
}
throw new Error("Value(" + value +") is not instance of type(" + type + ")");
}
}
}
validate();
}
_Enum.prototype = {
toString: function(){
return this.ns + "." + this.value + "(" + this.values + ")";
}
};
function _enum(type) {
function closure(ns, value, types){
return function(){
return new _Enum(ns, value, types, Array.prototype.slice.call(arguments));
}
}
for(var i in type){
scope[i] = {};
for(var k in type[i]){
scope[i][k] = closure(i, k, type[i][k]);
}
}
}
function match(value, matches){
return matches[value.value].apply(scope, value.values);
}
_enum({
Color: {
Red:[Number],
Green:[Number],
Blue:[Number],
RGB:[Number],
ARGB:[Number, Number]
}
});
var v = Color.ARGB(1, 0xff00ff);
var value = match(v, {
Red: function(col) {
return col.toString(16);
},
ARGB: function(alpha, col) {
return ((0xff000000 * alpha) + col).toString(16);
}
});
alert(value);​
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment