Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var Tree = exports.Tree = function(value, branches) {
- // @param: value => the value held by this node in the tree
- // @param: branches => the child nodes of this tree
- // @returns: the Tree
- this.value = value
- this.branches = branches
- }
- Tree.unfold = function(seed, transformer) {
- // @param: seed => the initial seed value for constructing the tree
- // @param: transformer(seed) => given a seed, return the node value for this
- // tree, along with the next generation of seeds
- // i.e. [value, [next generation of seeds]]
- // @returns: the unfolded Tree
- return _unfold(seed)
- function _unfold(seed) {
- var result = transformer(seed),
- value = result[0],
- seeds = result[1]
- return new Tree(value, seeds.map(_unfold))
- }
- }
- Tree.prototype.fold = function(transformer) {
- // @param: transformer(value, next generation of seeds) => given a node value
- // and the next generation of seeds, return a seed for this tree
- // (opposite of unfold)
- // @returns: a seed value representing this Tree
- return _fold(this)
- function _fold(tree) {
- return transformer(tree.value, tree.branches.map(_fold))
- }
- }
- Tree.prototype.map = function(transformer) {
- // @param: transformer(value) => given a node value, return a new node value
- // @returns: a new Tree
- return _map(this)
- function _map(tree) {
- return new Tree(transformer(tree.value), tree.branches.map(_map))
- }
- }
- Tree.prototype.traverse = function(visitor) {
- // @param: visitor(value, level) -> callback for traversal
- // @returns: nothing; used for side-effects
- var level = 1
- _visit(this)
- function _visit(tree) {
- visitor(tree.value, level)
- level++
- tree.branches.forEach(_visit)
- level--
- }
- }
- Tree.prototype.toString = function() {
- return this.fold(function(value, seeds) {
- return '<' + value + ': [' + seeds.join(',') + ']>'
- })
- }
- Tree.prototype.toPrettyString = function(indent) {
- indent = indent || '\t'
- var out = []
- this.traverse(function(value, level) {
- out.push(new Array(level).join(indent) + value)
- })
- return out.join('\n')
- }
- ////////////////////////////
- // A basic heap
- var t = Tree.unfold(1, function(seed) {
- return [seed, seed < 64 ? [(2 * seed), (2 * seed) + 1] : []]
- })
- console.log(t.toPrettyString())
Add Comment
Please, Sign In to add comment