]> git.r.bdr.sh - rbdr/serpentity/blob - lib/serpentity/node_collection.js
f5b1794a8a88f8fdf79255581a4871c9354f0d5d
[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 let node, types, property;
32
33 node = new this.type({});
34 node.entity = entity;
35 types = this.type.types;
36
37 for (property in types) {
38 if (types.hasOwnProperty(property)) {
39 node[property] = entity.getComponent(types[property]);
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;
58
59 found = -1;
60 this.nodes.forEach(function (node, i) {
61 if (node.entity === entity) {
62 found = i;
63 }
64 });
65
66 if (found >= 0) {
67 this.nodes.splice(found, 1);
68 return true;
69 }
70
71 return false;
72 }
73
74 /*
75 * Checks whether we already have nodes for this entity.
76 */
77 _entityExists (entity) {
78 let found, node;
79
80 found = false;
81 for (node of this.nodes) {
82 if (node.entity === entity) {
83 found = true;
84 }
85 }
86
87 return found;
88 }
89 };
90
91 if (typeof module !== 'undefined' && this.module !== module) {
92 module.exports = NodeCollection;
93 } else {
94 Serpentity.NodeCollection = NodeCollection;
95 }