-
Notifications
You must be signed in to change notification settings - Fork 21
/
enums.js
55 lines (53 loc) · 1.81 KB
/
enums.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
(function (exports) {
function copyOwnFrom(target, source) {
Object.getOwnPropertyNames(source).forEach(function(propName) {
Object.defineProperty(target, propName,
Object.getOwnPropertyDescriptor(source, propName));
});
return target;
}
function Symbol(name, props) {
this.name = name;
if (props) {
copyOwnFrom(this, props);
}
Object.freeze(this);
}
/** We don’t want the mutable Object.prototype in the prototype chain */
Symbol.prototype = Object.create(null);
Symbol.prototype.constructor = Symbol;
/**
* Without Object.prototype in the prototype chain, we need toString()
* in order to display symbols.
*/
Symbol.prototype.toString = function () {
return "|"+this.name+"|";
};
Object.freeze(Symbol.prototype);
Enum = function (obj) {
if (arguments.length === 1 && obj !== null && typeof obj === "object") {
Object.keys(obj).forEach(function (name) {
this[name] = new Symbol(name, obj[name]);
}, this);
} else {
Array.prototype.forEach.call(arguments, function (name) {
this[name] = new Symbol(name);
}, this);
}
Object.freeze(this);
}
Enum.prototype.symbols = function() {
return Object.keys(this).map(
function(key) {
return this[key];
}, this
);
}
Enum.prototype.contains = function(sym) {
if (! sym instanceof Symbol) return false;
return this[sym.name] === sym;
}
exports.Enum = Enum;
exports.Symbol = Symbol;
}(typeof exports === "undefined" ? this.enums = {} : exports));
// Explanation of this pattern: http://www.2ality.com/2011/08/universal-modules.html