-
Notifications
You must be signed in to change notification settings - Fork 0
/
Node.js
323 lines (277 loc) · 10.8 KB
/
Node.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/**
* The private properties of a Node instance.
* @type {WeakMap<Node, {parents: Set<Node>, children: Set<Node>, events: Object.<(string|symbol), Map<Node, boolean>>}>}
* @private
*/
const _private = new WeakMap();
/**
* Indicates the deleted Nodes. If no reference to the deleted Node exists,
* it will be removed from the WeakSet automatically.
* @type {WeakSet<Node>}
* @private
*/
const _deleted = new WeakSet();
/**
* This class is used to create networks of Nodes. Each Node is associated with some data
* and can be connected with other Nodes. Events can be registered to a Node and might
* be used to trigger a chain reaction within the network. This way implementations of
* connected graphs, neural networks, process structures and finite automatons are made easy.
* @class
* @throws {TypeError} Every method will throw a TypeError, if arguments are not as specified.
*/
class Node {
/**
* Constructs a new Node to use with other Nodes.
* @param {object} [data=null] The data associated with the new Node. Can be set later if not defined.
* @constructs Node
*/
constructor(data = null) {
if (typeof data !== 'object')
throw new TypeError("The data for a Node can only be an object.");
Object.defineProperties(this, {
data: {
value: data,
// NOTE optional: make late-assignment possible
// get: () => data,
// set: (value) => data === null && typeof value === 'object'
// ? data = value
// : undefined
}
});
_private.set(this, {
parents: new Set(),
children: new Set(),
events: {}
});
} // Node#constructor
/**
* Creates an outgoing connection from the current to another Node.
* @param {Node} node The Node to attach as child.
* @throws {Error} Throws an error, if you attach a Node to itself.
* @returns {Node} The current Node.
*/
attach(node) {
if (!(_isNode(this)))
throw new TypeError("Function call on an invalid Node.");
if (this === node)
throw new Error("You must not attach a Node to itself.");
if (!(_isNode(node)))
throw new TypeError("You can only attach valid Nodes.");
_private.get(this).children.add(node);
_private.get(node).parents.add(this);
return this;
} // Node#attach
/**
* An alias for Node#attach, reversing current Node and argument.
* @param {Node} node The Node to attach to as child.
* @throws {Error} Throws an error, if you attach a Node to itself.
* @returns {Node} The current Node.
*/
attachTo(node) {
if (!(_isNode(this)))
throw new TypeError("Function call on an invalid Node.");
if (this === node)
throw new Error("You must not attach a Node to itself.");
if (!(_isNode(node)))
throw new TypeError("You can only attach to valid Nodes.");
node.attach(this);
return this;
} // Node#attachTo
/**
* Removes an outgoing connection from the current Node.
* @param {Node} node The Node to detach from children.
* @returns {Node} The current Node.
*/
detach(node) {
if (!(_isNode(this)))
throw new TypeError("Function call on an invalid Node.");
if (!(_isNode(node)))
throw new TypeError("Detaching requires a valid Node.");
if (_private.get(this).children.delete(node))
_private.get(node).parents.delete(this);
return this;
} // Node#detach
/**
* An alias for Node#detach, reversing current Node and argument.
* @param {Node} node The Node to detach from as child.
* @returns {Node} The current Node.
*/
detachFrom(node) {
if (!(_isNode(this)))
throw new TypeError("Function call on an invalid Node.");
if (!(_isNode(node)))
throw new TypeError("You can only detach from valid Nodes.");
node.detach(this);
return this;
} // Node#detachFrom
/**
* Removes all ingoing and outgoing connections of the current Node and deletes it permanently.
* @param {boolean} [confirm=false] You must confirm deletion.
* @throws {Error} Throws an error, if you do not confirm the deletion.
* @returns {undefined} Nothing to return any more.
*/
delete(confirm = false) {
if (!(_isNode(this)))
throw new TypeError("Function call on an invalid Node.");
if (!confirm)
throw new Error("Deletion without confirmation will throw an error.");
const { parents, children } = _private.get(this);
parents.forEach(parent => _private.get(parent).children.delete(this));
children.forEach(child => _private.get(child).parents.delete(this));
// TODO evaluate if it is necessary to call detach for all children and detachFrom for all parents
_deleted.add(this);
_private.delete(this);
} // Node#delete
/**
* Indicates, if a Node has been deleted.
* @type {boolean}
*/
get deleted() {
return _deleted.has(this);
} // Node#deleted
/**
* Adds an event listener to the current Node.
* @param {(string|symbol)} event The name of the event.
* @param {function} callback The event callback.
* @returns {Node} The current Node.
*/
on(event, callback) {
if (!(_isNode(this)))
throw new TypeError("Function call on an invalid Node.");
if (!(_isEvent(event, callback)))
throw new TypeError("An event is identified by a string or a symbol and a callback function.");
let { events } = _private.get(this);
if (!Reflect.has(events, event))
events[event] = new Map();
events[event].set(callback, false);
return this;
} // Node#on
/**
* Adds an event listener to the current Node for a single call.
* @param {(string|symbol)} event The name of the event.
* @param {function} callback The event callback.
* @returns {Node} The current Node.
*/
once(event, callback) {
if (!(_isNode(this)))
throw new TypeError("Function call on an invalid Node.");
if (!(_isEvent(event, callback)))
throw new TypeError("An event is identified by a string or a symbol and a callback function.");
let { events } = _private.get(this);
if (!Reflect.has(events, event))
events[event] = new Map();
events[event].set(callback, true);
return this;
} // Node#once
/**
* Removes an event listener from the current Node.
* @param {(string|symbol)} event The name of the event.
* @param {function} callback The event callback.
* @returns {Node} The current Node.
*/
off(event, callback) {
if (!(_isNode(this)))
throw new TypeError("Function call on an invalid Node.");
if (!(_isEvent(event, callback)))
throw new TypeError("An event is identified by a string or a symbol and a callback function.");
let { events } = _private.get(this);
if (Reflect.has(events, event))
events[event].delete(callback);
return this;
} // Node#off
/**
* Triggers an event on the current Node with assigned arguments on the next event loop.
* @param {(string|symbol)} event The name of the event.
* @param {...any} args The arguments for the event callbacks.
* @returns {Node} The current Node.
*/
trigger(event, ...args) {
if (!(_isNode(this)))
throw new TypeError("Function call on an invalid Node.");
let { events } = _private.get(this);
if (Reflect.has(events, event) && events[event].size > 0)
events[event].forEach((once, callback, map) => {
if (once) map.delete(callback);
_makeEventCall(this, callback, args)
});
return this;
} // Node#trigger
/**
* Emits an event to all children of the current Node with assigned arguments.
* @param {(string|symbol)} event The name of the event.
* @param {...any} args The arguments for the event callbacks.
* @returns {Node} The current Node.
*/
emit(event, ...args) {
if (!(_isNode(this)))
throw new TypeError("Function call on an invalid Node.");
let { children } = _private.get(this);
children.forEach(child => child.trigger(event, ...args));
return this;
} // Node#emit
/**
* Emits an event to all parents of the current Node with assigned arguments.
* @param {(string|symbol)} event The name of the event.
* @param {...any} args The arguments for the event callbacks.
* @returns {Node} The current Node.
*/
emitBack(event, ...args) {
if (!(_isNode(this)))
throw new TypeError("Function call on an invalid Node.");
let { parents } = _private.get(this);
parents.forEach(parent => parent.trigger(event, ...args));
return this;
} // Node#emitBack
/**
* Indicates if an object is a valid Node.
* @param {(Node|*)} instance The instance to be tested.
* @returns {boolean} Indicator for been a Node.
*/
static isNode(instance) {
return _isNode(instance);
} // Node#isNode
} // Node
/**
* Indicates if an object is a valid Node.
* @param {(Node|*)} instance The instance to be tested.
* @returns {boolean} Indicator for been a Node.
*/
function _isNode(instance) {
return (instance instanceof Node) && !_deleted.has(instance);
} // _isNode
/**
* Indicates if event name and callback for an event have valid types.
* @param {(string|*)} event The event name to be tested.
* @param {(function|*)} callback The callback to be tested.
* @returns {boolean} Indicator for been a valid event.
*/
function _isEvent(event, callback) {
return event && (typeof event === 'string' || typeof event === 'symbol')
&& typeof callback === 'function';
} // _isEvent
/**
* Makes the actual call to an event callback, ignoring all errors.
* @param {Node} scope The current Node for this call.
* @param {function} callback The callback of an event.
* @param {Array} args The arguments passed to the trigger function.
* @returns immediateID
* @private
*/
function _makeEventCall(scope, callback, args) {
return setImmediate(() => {
// Prevents errors if a callback fails.
try {
let result = callback.apply(scope, args);
if (result instanceof Promise)
result.catch(err => console.error(err));
} catch (err) {
// NOTE The logging might be removed for productive use.
console.error(err);
}
});
} // _makeEventCall
/**
* @module Node
* @author Simon Petrac <[email protected]>
*/
module.exports = Node;