Guest User

Untitled

a guest
May 26th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. var Tree = exports.Tree = function(value, branches) {
  2. // @param: value => the value held by this node in the tree
  3. // @param: branches => the child nodes of this tree
  4. // @returns: the Tree
  5. this.value = value
  6. this.branches = branches
  7. }
  8.  
  9. Tree.unfold = function(seed, transformer) {
  10. // @param: seed => the initial seed value for constructing the tree
  11. // @param: transformer(seed) => given a seed, return the node value for this
  12. // tree, along with the next generation of seeds
  13. // i.e. [value, [next generation of seeds]]
  14. // @returns: the unfolded Tree
  15. return _unfold(seed)
  16.  
  17. function _unfold(seed) {
  18. var result = transformer(seed),
  19. value = result[0],
  20. seeds = result[1]
  21.  
  22. return new Tree(value, seeds.map(_unfold))
  23. }
  24. }
  25.  
  26. Tree.prototype.fold = function(transformer) {
  27. // @param: transformer(value, next generation of seeds) => given a node value
  28. // and the next generation of seeds, return a seed for this tree
  29. // (opposite of unfold)
  30. // @returns: a seed value representing this Tree
  31. return _fold(this)
  32.  
  33. function _fold(tree) {
  34. return transformer(tree.value, tree.branches.map(_fold))
  35. }
  36. }
  37.  
  38. Tree.prototype.map = function(transformer) {
  39. // @param: transformer(value) => given a node value, return a new node value
  40. // @returns: a new Tree
  41. return _map(this)
  42.  
  43. function _map(tree) {
  44. return new Tree(transformer(tree.value), tree.branches.map(_map))
  45. }
  46. }
  47.  
  48. Tree.prototype.traverse = function(visitor) {
  49. // @param: visitor(value, level) -> callback for traversal
  50. // @returns: nothing; used for side-effects
  51. var level = 1
  52. _visit(this)
  53.  
  54. function _visit(tree) {
  55. visitor(tree.value, level)
  56. level++
  57. tree.branches.forEach(_visit)
  58. level--
  59. }
  60. }
  61.  
  62. Tree.prototype.toString = function() {
  63. return this.fold(function(value, seeds) {
  64. return '<' + value + ': [' + seeds.join(',') + ']>'
  65. })
  66. }
  67.  
  68. Tree.prototype.toPrettyString = function(indent) {
  69. indent = indent || '\t'
  70.  
  71. var out = []
  72. this.traverse(function(value, level) {
  73. out.push(new Array(level).join(indent) + value)
  74. })
  75. return out.join('\n')
  76. }
  77.  
  78. ////////////////////////////
  79.  
  80. // A basic heap
  81. var t = Tree.unfold(1, function(seed) {
  82. return [seed, seed < 64 ? [(2 * seed), (2 * seed) + 1] : []]
  83. })
  84.  
  85. console.log(t.toPrettyString())
Add Comment
Please, Sign In to add comment