Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Additional functions. #10

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
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.

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


const len = currNode.child.length;
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;
const callback = function(n) {
if (n.name === whereAdd) {
parent = n;
}
};
this.isHave(callback);

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


const 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);