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