Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.77 KB | None | 0 0
  1. var root1 = new Tree(1);
  2. // console.log(root1);
  3. var branch2 = root1.addChild(2);
  4. var branch3 = root1.addChild(3);
  5. var leaf4 = branch2.addChild(4);
  6. var leaf5 = branch2.addChild(5);
  7. var leaf6 = branch3.addChild(6);
  8. var leaf7 = branch3.addChild(7);
  9. var newTree = root1.map(function (value) {
  10. return value * 2;
  11. })
  12. console.log(newTree.value) // 2
  13. console.log(newTree.children[0].value) // 4
  14. console.log(newTree.children[1].value) // 6
  15. console.log(newTree.children[0].children[1].value) // 10
  16. console.log(newTree.children[1].children[1].value) // 14
  17.  
  18. Tree.prototype.map = function (callback) {
  19. // return a new tree with the same structure as `this`, with values generated by the callback
  20. var mapped = new Tree(this.value);
  21. mapped.value = callback(this.value);
  22. mapped.children = this.children;
  23.  
  24. if (mapped.children.length === 0) {
  25. return mapped;
  26. }
  27.  
  28. for (var i = 0; i < mapped.children.length; i++) {
  29. mapped.children[i].value = callback(mapped.children[i].value);
  30. };
  31.  
  32. return mapped;
  33.  
  34. };
  35.  
  36. var root1 = new Tree(1);
  37. // console.log(root1);
  38. var branch2 = root1.addChild(2);
  39. var branch3 = root1.addChild(3);
  40. var leaf4 = branch2.addChild(4);
  41. var leaf5 = branch2.addChild(5);
  42. var leaf6 = branch3.addChild(6);
  43. var leaf7 = branch3.addChild(7);
  44. var newTree = root1.map(function (value) {
  45. return value * 2;
  46. })
  47. console.log(newTree.value) // 2 --> my functions for this
  48. console.log(newTree.children[0].value) // 4 --> my function works for this
  49. console.log(newTree.children[1].value) // 6 ---> my function works
  50. console.log(newTree.children[0].children[1].value) // 10 ---> doesn't work
  51. console.log(newTree.children[1].children[1].value) // 14 ---> doesn't work
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement