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