forked from node-modules/enums
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
59 lines (53 loc) · 1.28 KB
/
index.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
56
57
58
59
/**
* MIT Licensed
*
* Authors:
* 汤尧 <tangyao@taobao.com>
*/
'use strict';
function Enums(items) {
items = items || [];
if (items.constructor.name === 'Enums') {
items = items.enums;
}
this.enums = [];
if (!Array.isArray(items)) {
items = [items];
}
for (var i = 0, len = items.length; i < len; i++) {
var item = items[i];
if (typeof item === 'string') {
item = { name: item };
}
item.ordinal = i;
Object.defineProperty(item, 'eql', {
configurable: true,
enumerable: false,
value: function(that) {
if (!that || !that.name) {
return false;
}
return (this.$name !== undefined && that.$name !== undefined && this.$name !== null && that.$name !== null && this.$name === that.$name) || this.name === that.name;
},
});
this[item.$name || item.name] = item;
this.enums.push(item);
}
}
Enums.prototype.getByCode = function(code) {
return this.getBy('code', code);
};
Enums.prototype.getBy = function(name, val) {
var enums = this.enums;
for (var i = 0, len = enums.length; i < len; i++) {
var item = enums[i];
if (item[name] === val) {
return item;
}
}
return null;
};
Enums.prototype.values = function() {
return this.enums;
};
module.exports = Enums;