-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtreewithpath.js
394 lines (351 loc) · 11.4 KB
/
treewithpath.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/**
* The class of the TreeWithPath tree
*/
class Tree
{
/**
* Creates a tree
*
* @param data Tree root node data. The name of the root node is always root
* @constructor
* @example
* const Tree = require("treewithpath");
* const tree = new Tree({ text: "Hello, world!", "otherText": "hoI!" });
*/
constructor(data) {
this._root = new Node("root", data, this);
}
/**
* Root node of this tree
*
* @returns {Node} Root node
* @this {Tree}
*/
get root() {
return this._root;
}
/**
* Adds a node to the tree and returns it
*
* @param {string} name The name of the node to add
* @param data The data of the node to be created
* @param {string} path The path to the parent of the node to create
* @this {Tree} Tree
* @return {Node} Created node
* @throws {TreeError} In case the node already exists
* @example
* tree.add("node2", { text: "Hello, world!", "otherText": "hoI!" }, "/node1");
*/
add(name, data, path) {
if (this.has(Tree.joinPath(path, name))) {
throw new TreeError("This node already exists");
}
const node = new Node(name, data, this);
this.get(path)._children.push(node);
return node;
}
/**
* Gets the node at the specified path
*
* @param {string} path The path to the node to receive
* @param {boolean} error Optional parameter. The default is true. If true, an exception will be thrown if the path is incorrect. Otherwise, null will be returned
* @this {Tree} Tree
* @returns {Node | null} The resulting node or null if error = false and node not found
* @throws {TreeError} In case the node is not found and error = true
* @example
* tree.get("/node1");
*/
get(path, error = true) {
let current = [this.root];
const parsedPath = parsePath(path);
for (const [ index, node ] of parsedPath.entries()) {
const currentNode = current.find(currentNode => currentNode.name === node);
if (currentNode !== undefined) {
current = currentNode._children;
if (index === parsedPath.length - 1) {
return currentNode;
}
} else if (error) {
throw new TreeError(`${node}: Node not exists`);
} else {
return null;
}
}
}
/**
* Deletes the node and returns it at the specified path
*
* @param {string} path The path to the node to be deleted
* @this {Tree} Tree
* @returns {Node} A deleted node that no longer contains children. Children are permanently deleted
* @throws {TreeError} In case the node is not found
* @example
* tree.remove("/node1");
*/
remove(path) {
const node = this.get(path);
node.remove();
return node;
}
/**
* Calls a callback for each node in the tree
*
* @param {Function} callback A function called for each node of the tree. The node in the first argument is passed to the function
* @this {Tree} Tree
* @example
* tree.traverse(node => {
* console.log(node.name);
* });
*/
traverse(callback) {
this.root.traverse(callback);
}
/**
* Returns a tree object suitable for storage in JSON format. This method is mainly used by the JSON.stringify function
*
* @this {Tree} Tree
* @returns {object} A tree object suitable for storage in JSON format
* @example
* tree.toJSON(); // { name: "root", data: { text: "Hello, world!", "otherText": "hoI!" }, children: [{ name: "node1", data: { text: "Hello, world!", "otherText": "hoI!" }, children: [{ name: "node2", data: {text: "Hello, world!", "otherText": "hoI!" }, children: [] }] }
*/
toJSON() {
return this.root.toJSON();
}
/**
* Checks a node for existence in a tree
*
* @param {string} path The path to the node to check
* @returns {boolean} True if the node exists and false if it does not exist
* @this {Tree} Tree
* @example
* tree.has("/notExists/child") // false
* tree.has("/exists") // true
*/
has(path) {
return this.get(path, false) !== null;
}
/**
* Creates a tree from an object that returns the toJSON() method
*
* @param {object} json A tree object suitable for storage in JSON format
* @returns {Tree} Created tree
* @example
* const tree = Tree.fromJSON({ name: "root", data: { text: "Hello, world!", "otherText": "hoI!" }, children: [{name: "node1", data: {text: "Hello, world!", "otherText": "hoI!"}, children: [{name: "node2", data: {text: "Hello, world!", "otherText": "hoI!"}, children: [] }] });
*/
static fromJSON(json) {
const tree = new Tree(json.data);
function recurse(recurseJson, addTo) {
for (const node of recurseJson) {
recurse(node.children, addTo.addChild(node.name, node.data));
}
};
recurse(json.children, tree.root);
return tree;
}
/**
* Connects the two specified paths into one.
*
* @param {string} firstPath First path
* @param {sting} secondPath Second path
* @returns {string} United path
* @example
* Tree.joinPath("/node1", "node2") // /node1/node2
*/
static joinPath(firstPath, secondPath) {
if (firstPath.endsWith("/") && secondPath.startsWith("/")) {
return firstPath.substr(0, firstPath.length - 1) + secondPath;
} else if (firstPath.endsWith("/") || secondPath.endsWith("/") || secondPath.startsWith("/")) {
return firstPath + secondPath;
} else {
return `${firstPath}/${secondPath}`;
}
}
}
/**
* Node class
*/
class Node
{
/**
* Creates an instance of a node. Do not use this constructor yourself. To add nodes, use the add and addChild methods
*
* @param {string} name The name of the node
* @param data Node data
* @param {Tree} tree The tree to which the node will belong
* @constructor
*/
constructor(name, data, tree) {
/**
* Name of this node
*/
this.name = name;
/**
* Data of this node
*/
this.data = data;
/** @private */
this._children = [];
this._tree = tree;
}
/**
* The tree to which the node will belong
*
* @returns {Tree} Tree to which the node will belong
* @this {Node}
*/
get tree() {
return this._tree;
}
/**
* Getter to get the path to this node
*
* @returns {string} The path to this node
* @this {Node} Node
* @throws {TreeError} In case this node does not belong to any tree
*/
get path() {
if (this.tree == null) {
throw new TreeError("This node does not belong to any tree");
}
const parentsArray = [];
function recurse(node) {
if (node != null) {
parentsArray.push(node);
return recurse(node.parent);
} else {
return parentsArray;
}
}
const pathArray = recurse(this);
pathArray.pop();
return `/${pathArray.map(node => node.name).reverse().join("/")}`;
}
/**
* Getter to get the parent of this node
*
* @returns {Node} Parent of this node
* @this {Node} Node
* @throws {TreeError} In case this node does not belong to any tree
*/
get parent() {
if (this.tree == null) {
throw new TreeError("This node does not belong to any tree");
}
if (this.tree.root._children.includes(this)) {
return this.tree.root;
}
function recurse(children) {
const parent = children.find((item) => item._children.includes(this));
if (parent != null) {
return parent;
} else {
for (const child of children) {
return recurse.call(this, child._children);
}
}
}
return recurse.call(this, this.tree.root._children);
}
/**
* A getter that returns an array of children of the given node
*
* @this {Node} Node
* @returns {Array} Array of children for this node
*/
get children() {
return this._children;
}
/**
* Deletes the given node and its children
*
* @this {Node} Node
* @throws {TreeError} In case this node does not belong to any tree
* @throws {TreeError} If this node is the root
*/
remove() {
if (this.tree == null) {
throw new TreeError("This node does not belong to any tree");
}
if (this.parent == null) {
throw new TreeError("Cannot remove root node");
} else {
this.parent._children.splice(this.parent._children.indexOf(this), 1);
this._tree = null;
this._children = null;
}
}
/**
* Adds a child to this node
*
* @param {string} name The name of the node to add
* @param data The data of the node being added
* @this {Node} Node
* @throws {TreeError} In case this node does not belong to any tree
* @throws {TreeError} In case the node already exists
*/
addChild(name, data) {
if (this.tree == null) {
throw new TreeError("This node does not belong to any tree")
}
if (this.tree.has(Tree.joinPath(this.path, name))) {
throw new TreeError("This node already exists");
}
const node = new Node(name, data, this.tree);
this._children.push(node);
return node;
}
/**
* Returns a node object suitable for storage in JSON format. This method is mainly used by the JSON.stringify function
*
* @this {Node} Node
* @returns {object} A node object suitable for storage in JSON format
* @example
* node.toJSON(); // { name: "root", data: { text: "Hello, world!", "otherText": "hoI!" }, children: [{ name: "node1", data: {text: "Hello, world!", "otherText": "hoI!" }, children: [{ name: "node2", data: { text: "Hello, world!", "otherText": "hoI!" }, children: [] }] }
*/
toJSON() {
return { name: this.name, data: this.data, children: this._children };
}
/**
* Calls a callback for each child node of this node
*
* @param {Function} callback A function called for child node of this node The node in the first argument is passed to the function
* @this {Node} Node
* @example
* node.traverse(node => {
* console.log(node.name);
* });
*/
traverse(callback) {
function recurse(node) {
callback(node);
for (const child of node._children) {
recurse(child);
}
}
recurse(this);
}
}
/**
* It is a TreeWithPath error class.
* @private
*/
class TreeError extends Error {
constructor(message) {
super(message);
this.name = "TreeError";
}
}
/** @private */
function parsePath(path) {
if (path.startsWith("/")) {
const pathArray = path.split("/");
pathArray[0] = "root";
if (pathArray[pathArray.length - 1] == "") {
pathArray.pop();
}
return pathArray;
} else {
throw new TreeError("Wrong path");
}
}
module.exports = Tree;