forked from qiao/ces.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentitylist.js
134 lines (117 loc) · 2.7 KB
/
entitylist.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
var Class = require('./class');
/**
* The entity node is a wrapper around an entity, to be added into
* the entity list.
* @class
*/
var EntityNode = Class.extend({
init: function (entity) {
this.entity = entity;
this.prev = null;
this.next = null;
}
});
/**
* The entity list is a doubly-linked-list which allows the
* entities to be added and removed efficiently.
* @class
*/
var EntityList = module.exports = Class.extend({
/**
* @constructor
*/
init: function () {
/**
* @public
* @readonly
*/
this.head = null;
/**
* @public
* @readonly
*/
this.tail = null;
/**
* @public
* @readonly
*/
this.length = 0;
/**
* Map from entity id to entity node,
* for O(1) find and deletion.
* @private
*/
this._entities = {};
},
/**
* Add an entity into this list.
* @public
* @param {Entity} entity
*/
add: function (entity) {
var node = new EntityNode(entity);
if (this.head === null) {
this.head = this.tail = node;
} else {
node.prev = this.tail;
this.tail.next = node;
this.tail = node;
}
this.length += 1;
this._entities[entity.id] = node;
},
/**
* Remove an entity from this list.
* @public
* @param {Entity} entity
*/
remove: function (entity) {
var node = this._entities[entity.id];
if (node === undefined) {
return;
}
if (node.prev === null) {
this.head = node.next;
} else {
node.prev.next = node.next;
}
if (node.next === null) {
this.tail = node.prev;
} else {
node.next.prev = node.prev;
}
this.length -= 1;
delete this._entities[entity.id];
},
/**
* Check if this list has the entity.
* @public
* @param {Entity} entity
* @return {Boolean}
*/
has: function (entity) {
return this._entities[entity.id] !== undefined;
},
/**
* Remove all the entities from this list.
* @public
*/
clear: function () {
this.head = this.tail = null;
this.length = 0;
this._entities = {};
},
/**
* Return an array holding all the entities in this list.
* @public
* @return {Array}
*/
toArray: function () {
var array, node;
array = [];
for (node = this.head; node; node = node.next) {
array.push(node.entity);
}
return array;
}
});