]> git.r.bdr.sh - rbdr/serpentity/blob - lib/serpentity/node_collection.js
73998b123500f36a6a3b828b672d10720235bfe8
[rbdr/serpentity] / lib / serpentity / node_collection.js
1 'use strict';
2
3 const Events = require('events');
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 const NodeCollection = class NodeCollection extends Events {
14
15 constructor(config) {
16
17 super();
18
19 this.nodes = [];
20 this.type = null;
21
22 Object.assign(this, config);
23 }
24
25 /*
26 * Creates a node for an entity if it matches, and adds it to the
27 * node list.
28 *
29 * Returns true if added, false otherwise.
30 */
31 add(entity) {
32
33 if (this.type.matches(entity) && !this._entityExists(entity)) {
34
35 const node = new this.type({});
36 const types = this.type.types;
37 const typeNames = Object.keys(types);
38
39 node.entity = entity;
40
41 for (const typeName of typeNames) {
42 node[typeName] = entity.getComponent(types[typeName]);
43 }
44
45 this.nodes.push(node);
46 this.emit('nodeAdded', { node });
47
48 return true;
49 }
50
51 return false;
52 }
53
54 /*
55 * Removes an entity by removing its related node from the list of nodes
56 *
57 * returns true if it was removed, false otherwise.
58 */
59 remove(entity) {
60
61 let foundIndex = -1;
62
63 const found = this.nodes.some((node, i) => {
64
65 if (node.entity === entity) {
66 foundIndex = i;
67 return true;
68 }
69 });
70
71 if (found) {
72 this.nodes.splice(foundIndex, 1);
73 this.emit('nodeRemoved', { node });
74 }
75
76 return found;
77 }
78
79 /*
80 * Checks whether we already have nodes for this entity.
81 */
82 _entityExists(entity) {
83
84 let found = false;
85
86 for (const node of this.nodes) {
87 if (node.entity === entity) {
88 found = true;
89 }
90 }
91
92 return found;
93 }
94 };
95
96 module.exports = NodeCollection;