forked from ibolmo/task-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollection.js
98 lines (79 loc) · 2.14 KB
/
Collection.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
var Q = require('q');
var Collection = function(set, Base){
if (!set) set = [];
if (!set.pop) set = [set];
this.set = (set || []).map(function(datum){
return datum instanceof Base ? datum : new Base(datum);
});
this.Base = Base;
};
Collection.prototype.add = function(data){
if (!data.pop) data = [data];
data.forEach(function(datum){
if (!(datum instanceof this.Base)) datum = new this.Base(datum);
if (!this.find(datum.getId())) this.set.push(datum);
}, this);
};
Collection.prototype.count = function(){
return this.set.length;
};
Collection.prototype.find = function(id){
return this.set.filter(function(datum){
return datum.getId() == id;
})[0];
};
Collection.prototype.forEach = function(cb, bind){
return this.set.forEach(cb, bind);
};
Collection.prototype.get = function(i){
return this.set[i];
};
Collection.prototype.getPending = function(){
var pending = [];
this.set.forEach(function(datum){
pending = pending.concat(datum.getPending());
});
return pending;
};
Collection.prototype.hasPending = function(){
return this.set.some(function(datum){
return datum.hasPending();
});
};
Collection.prototype.waitForPending = function(){
return Q.all(this.getPending());
};
Collection.prototype.indexOf = function(datum){
var id = datum.getId();
for (var i = 0; i < this.set.length; i++) if (id == this.set[i].getId()){
return i;
}
return -1;
};
Collection.prototype.map = function(cb, bind){
return this.set.map(cb, bind);
};
Collection.prototype.last = function(){
return this.set[this.set.length - 1];
};
Collection.prototype.push = function(datum){
return this.set.push(datum);
};
Collection.prototype.remove = function(data){
if (!data.pop) data = [data];
var self = this;
data.forEach(function(datum){
if (!(datum instanceof self.Base)) datum = new self.Base(datum);
var index = self.indexOf(datum);
if (index > -1) self.set.splice(index, 1);
});
};
Collection.prototype.sort = function(comparator){
return this.set.sort(comparator);
};
Collection.prototype.toObject = function(){
return this.set.map(function(datum){
return datum.toObject ? datum.toObject() : datum;
});
};
module.exports = Collection;