]> git.r.bdr.sh - rbdr/serpentity/blob - lib/serpentity/node_collection.js
7c519912364c3a7559b8f0131a27ce90db66f909
[rbdr/serpentity] / lib / serpentity / node_collection.js
1 'use strict';
2
3 /* global Serpentity */
4
5 /*
6 * Node Collections contain nodes, in order to keep the lists of nodes
7 * that belong to each type.
8 *
9 * It has a type which is the class name of the node, and an array of
10 * instances of that class.
11 */
12
13 let NodeCollection = class NodeCollection {
14
15 constructor (config) {
16 this.nodes = [];
17 this.type = null;
18
19 Object.assign(this, config || {});
20 }
21
22 /*
23 * Creates a node for an entity if it matches, and adds it to the
24 * node list.
25 *
26 * Returns true if added, false otherwise.
27 */
28 add (entity) {
29
30 if (this.type.matches(entity) && !this._entityExists(entity)) {
31
32 let node = new this.type({});
33 let types = this.type.types;
34
35 node.entity = entity;
36
37 for (let typeName in types) {
38 if (types.hasOwnProperty(typeName)) {
39 node[typeName] = entity.getComponent(types[typeName]);
40 }
41 }
42
43 this.nodes.push(node);
44
45 return true;
46 }
47
48 return false;
49 }
50
51 /*
52 * Removes an entity by removing its related node from the list of nodes
53 *
54 * returns true if it was removed, false otherwise.
55 */
56 remove (entity) {
57 let found = -1;
58
59 this.nodes.forEach(function (node, i) {
60 if (node.entity === entity) {
61 found = i;
62 }
63 });
64
65 if (found >= 0) {
66 this.nodes.splice(found, 1);
67 return true;
68 }
69
70 return false;
71 }
72
73 /*
74 * Checks whether we already have nodes for this entity.
75 */
76 _entityExists (entity) {
77 let found = false;
78
79 for (let node of this.nodes) {
80 if (node.entity === entity) {
81 found = true;
82 }
83 }
84
85 return found;
86 }
87 };
88
89 if (typeof module !== 'undefined' && this.module !== module) {
90 module.exports = NodeCollection;
91 } else {
92 Serpentity.NodeCollection = NodeCollection;
93 }