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
78 changes: 78 additions & 0 deletions JavaScript/4-newfunc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
'use strict';

function Node(parent, name, data) {
this.name = name;
this.data = data;
if (parent) {
this.parent = parent;
parent[name] = this;
}
this.child = [];
}

function Tree(name, data) {
this.root = new Node(null, name, data);
}

Tree.prototype.visitDepth = function(callback) {

(function recursive(currNode) {
Copy link
Member

Choose a reason for hiding this comment

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

What is a purpose of this IIFE (immediately-invoked function expression) ?

Copy link
Author

Choose a reason for hiding this comment

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

На парі показали такий варіант реалізації - вирішила спробувати, не більше того.


let len = currNode.child.length,
Copy link
Member

Choose a reason for hiding this comment

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

const len = currNode.child.length;

num;
Copy link
Member

Choose a reason for hiding this comment

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

let num;

for (num = 0; num < len; ++num) {
recursive(currNode.child[num]);
}

callback(currNode);
})(this.root);
};

Tree.prototype.isHave = function(callback) {
Copy link
Member

Choose a reason for hiding this comment

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

Tree.has(node) returns boolean, no need callback but where is node argument to check?

this.visitDepth.call(this, callback);
};

Tree.prototype.addData = function(name, data, whereAdd) {
let parent = null,
callback = function(n) {
Copy link
Member

Choose a reason for hiding this comment

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

Лучше отдельно объявлять

if (n.name === whereAdd) {
parent = n;
}
};
this.isHave(callback);

let node = new Node(parent, name, data);
if (parent) {
parent.child.push(node);
node.parent = parent;
} else {
throw new Error('Parent not exist!');
}
};


let tree = new Tree('one', 1);

tree.root.child.push(new Node(tree, 'two', 2));

tree.root.child.push(new Node(tree, 'three', 3));

tree.root.child.push(new Node(tree, 'four', 4));

tree.root.child[0].child.push(new Node(tree.root.child[0], 'five', 5));

tree.root.child[0].child.push(new Node(tree.root.child[0], 'six', 6));

tree.root.child[2].child.push(new Node(tree.root.child[2], 'seven', 7));


tree.isHave(n => {
if (n.name === 'five') {
console.dir(n);
}
});

tree.visitDepth(n => console.dir(n));

tree.addData('qwe', 456, 'two');
console.dir(tree);