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);
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 ()
This happens, when object's property refers to the object itself. Consider the code:
// define some object
const a = { foo: 1 };
// add a property referring to the object
a.bar = a;
console.log(JSON.stringify(a)); // TypeError
I feel dumb... I left in insert() two this, not this.tree. Thanks, @Aziza for explaining this <ref *1> to me!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With