Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions JavaScript/4-class.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
'use strict';

class Node {

constructor(parent, name, data) {
this.name = name;
this.data = data;
this.childs = [];
if (parent) {
this.parent = parent;
parent.childs.push(this);
}
}

findAll(name) { // Find all nodes with specified name
let arr = [];
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

const

if (this.name === name) arr.push(this);
for (let n of this.childs) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут ходить по массиву обычным циклом, for..of пока медленный

arr = arr.concat(n.findAll(name));
}

return arr;
}

findFirst(name) { //Find first instance
if (this.name === name) return this;
for (let n of this.childs) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

тоже без for..of лучше избавиться, а переменную содавать до цикла:

let i;
for (i = 0; ...

это работает быстрее

return n.findFirst(name);
}
}

find(name, callback) { //Call function for each found node
const nodes = this.findAll(name);
if (nodes.length > 0)
for (let n of this.findAll(name))
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

со скобками {} будет лучше и if и for

callback(n);
}

setParent(newParent) { // Sets new parent for this node
this.parent.childs.pop(this.parent.childs.indexOf(this));
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это таб?

this.parent = newParent;
this.parent.childs.push(this);
}
}

const root = new Node(null, 'root', {});
const n1 = new Node(root, 'searched', {});
const n2 = new Node(root, 'n2', {});
const n12 = new Node(n1, 'searched', {});


console.log('findAll("searched") -', root.findAll('searched'));
console.log('findFirst("searched") -', root.findFirst('searched'));
root.find('n2', n => {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот тут {} можно опустить
n => console.log(...

console.log('parent - ', n.parent);
});
n12.setParent(root);
console.log('n12 new parent -', n12.parent);