I'm trying to copy the Tree which one has value, children[], addChild(), map(callback). Passed all test about addChild() but not on map(callback). I'm using Jest and code is like bellow.
The method 'map' should return the Tree which one has same shape but calculated value in original Tree. And it should Not be the old one but new made one.(shallow copy)
I use Object.assign() to make shallow-copied Tree and executed the callback method on all node. But still not passed on test: should return an identical tree when the map function is identity (depth 1)
Please take a look and give an advice. thank you.
Test File
it("should return an identical tree when the map function is identity (depth 2)", function() {
// this "identity" function returns the same value that was passed in
var identity = function(value) {
return value;
};
// create a tree with some values
// depth: 0
var input = new Tree(1);
// depth: 1
input.addChild(2);
input.addChild(3);
// depth: 2
input.children[0].addChild(4);
input.children[0].addChild(5);
input.children[1].addChild(6);
input.children[1].addChild(8);
var result = input.map(identity);
// the input and output trees should have identical values
verifyTree(result, input);
});
const verifyTree = function(result, expectation) {
expect(result).toBeInstanceOf(Tree);
expect(result.value).toEqual(expectation.value);
expect(result).not.toBe(expectation);
expect(result.children).toHaveLength(expectation.children.length);
for (var i = 0; i < result.children.length; i++) {
verifyTree(result.children[i], expectation.children[i]); // and each child is also verified
}
};
tree file
var Tree = function(value) {
this.value = value;
this.children = [];
};
Tree.prototype.addChild = function(child) {
// your code here
let newChild;
if(typeof child === 'number'){
newChild = new Tree(child);
}else{
newChild = child
}
this.children.push(newChild);
};
Tree.prototype.map = function(callback) {
let copied = new Tree();
copied = Object.assign(new Tree(),this);
// recusion
function preorder(curNode){
if(curNode){
let newValue = curNode.value;
curNode.value = callback(newValue);
if(curNode.children){
for(let i=0 ; i<curNode.children.length ; i++){
preorder(curNode.children[i]);
}
}
}
}
preorder(copied);
return copied;
};
And the error message is like this. error message