As per the topic, I couldn't find anything specific about this on the internet.
What is <ref *1>
in the output I get before the class name even though I call the property "tree"? Reference... to what, and why if I call property? And how to fix it?
CLI Output:
> $ node binary-search-tree.js
<ref *1> BinarySearchTree { tree: [Circular *1] }
This is my code (learning algorithms):
const addNode = (base, num) => {
// base = {number, left?, right?}
if (num <= base.number) {
if (base.left) {
base.left = addNode(base.left, num);
} else base.left = { number: num };
}
if (num > base.number) {
if (base.right) {
base.right = addNode(base.right, num);
} else base.right = { number: num };
}
return base;
};
class BinarySearchTree {
constructor(baseValue) {
this.tree = { number: baseValue };
}
get data() {
return this.tree;
}
get right() {
throw new Error("Remove this statement and implement this function");
}
get left() {
throw new Error("Remove this statement and implement this function");
}
insert(nums) {
if (typeof nums === "number") {
this.tree = addNode(this, nums);
return;
}
for (let number of nums) {
this.tree = addNode(this, number);
}
}
each() {
throw new Error("Remove this statement and implement this function");
}
}
const lolTree = new BinarySearchTree(5);
lolTree.insert(58);
lolTree.insert([2, 7, 4, 100]);
lolTree.insert(55);
console.log(lolTree.tree);
CodePudding user response:
This is reference index for showing a circular reference.
Meaning that, there's some circular structure in your object.
You can also see it's circular by running:
JSON.stringify(lolTree.tree)
which will result in:
VM829:1 Uncaught TypeError: Converting circular structure to JSON --> starting at object with constructor 'BinarySearchTree' --- property 'tree' closes the circle at JSON.stringify ()
CodePudding user response:
I feel dumb... I left in insert()
two this
, not this.tree
. Thanks, @Aziza for explaining this <ref *1>
to me!
CodePudding user response:
addNode should probably be:
const addNode = (base, num) => {
// base = {number, left?, right?}
if (num <= base.number) {
if (base.left) {
addNode(base.left, num);
} else {
base.left = { number: num };
}
}
else {
if (base.right) {
addNode(base.right, num);
} else {
base.right = { number: num };
}
}
};
to avoid the circular reference mentioned by @aziza; edit: changed second if to an else - it is either left or right, so if it isn't left...