Created
May 25, 2017 19:21
-
-
Save r3b/d1310615bb2eaa338ed89ef5c3d88c6b to your computer and use it in GitHub Desktop.
ES5 ENUM implementation
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
function ENUM(){ | |
return Object.create({}, { | |
add: { | |
value: function (name) { | |
name = name.replace(/\s/, '_').replace(/\W/, '').toUpperCase(); | |
var ptr = this; | |
Object.defineProperty(ptr, name, { | |
enumerable: true, | |
configurable: false, | |
writable: false, | |
value: 1 << Object.keys(ptr).length | |
}); | |
}, | |
writable: false, | |
enumerable: false, | |
configurable: false | |
}, | |
valueOf: { | |
value: function (val) { | |
return (function (ptr) { | |
return Object.keys(ptr).filter(function (key) { | |
return ptr[key] === val; | |
}).pop(); | |
})(this); | |
}, | |
writable: false, | |
enumerable: false, | |
configurable: false | |
}, | |
get: { | |
value: function (key) { | |
return (function (ptr) { | |
return ptr[key]; | |
})(this); | |
}, | |
writable: false, | |
enumerable: false, | |
configurable: false | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment