Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var root1 = new Tree(1);
- // console.log(root1);
- var branch2 = root1.addChild(2);
- var branch3 = root1.addChild(3);
- var leaf4 = branch2.addChild(4);
- var leaf5 = branch2.addChild(5);
- var leaf6 = branch3.addChild(6);
- var leaf7 = branch3.addChild(7);
- var newTree = root1.map(function (value) {
- return value * 2;
- })
- console.log(newTree.value) // 2
- console.log(newTree.children[0].value) // 4
- console.log(newTree.children[1].value) // 6
- console.log(newTree.children[0].children[1].value) // 10
- console.log(newTree.children[1].children[1].value) // 14
- Tree.prototype.map = function (callback) {
- // return a new tree with the same structure as `this`, with values generated by the callback
- var mapped = new Tree(this.value);
- mapped.value = callback(this.value);
- mapped.children = this.children;
- if (mapped.children.length === 0) {
- return mapped;
- }
- for (var i = 0; i < mapped.children.length; i++) {
- mapped.children[i].value = callback(mapped.children[i].value);
- };
- return mapped;
- };
- var root1 = new Tree(1);
- // console.log(root1);
- var branch2 = root1.addChild(2);
- var branch3 = root1.addChild(3);
- var leaf4 = branch2.addChild(4);
- var leaf5 = branch2.addChild(5);
- var leaf6 = branch3.addChild(6);
- var leaf7 = branch3.addChild(7);
- var newTree = root1.map(function (value) {
- return value * 2;
- })
- console.log(newTree.value) // 2 --> my functions for this
- console.log(newTree.children[0].value) // 4 --> my function works for this
- console.log(newTree.children[1].value) // 6 ---> my function works
- console.log(newTree.children[0].children[1].value) // 10 ---> doesn't work
- console.log(newTree.children[1].children[1].value) // 14 ---> doesn't work
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement