Skip to content

Commit

Permalink
Complete treeMap.js
Browse files Browse the repository at this point in the history
  • Loading branch information
fay-jai committed Jan 1, 2015
1 parent 017f8b1 commit d90452b
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions treeMap/treeMap.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
* newTree.value // 2
* newTree.children[0].value // 4
* newTree.children[1].value // 6
* newTree.children[0].children[1] // 10
* newTree.children[1].children[1] // 14
* newTree.children[0].children[1].value // 10
* newTree.children[1].children[1].value // 14
* root1.value // still 1
*
*
Expand All @@ -38,13 +38,35 @@
* Basic tree that stores a value.
*/

var Tree = function(value){
var Tree = function (value){
this.value = value;
this.children = [];
};

Tree.prototype.map = function (callback) {
// return a new tree with the same structure as `this`, with values generated by the callback
// create a new tree with value equal to after being modified by callback
var newTree = new Tree ( callback.call(null, this.value) );

// for each child in the original tree
this.children.forEach(function (child) {
// call child.map with the same callback
var result = child.map( callback );
// append the result of this call to new tree
newTree.addChild( result );
});

// return new tree
return newTree;
};

Tree.prototype.mapInPlace = function (callback) {
this.value = callback.call( null, this.value );

// for each child in tree
this.children.forEach(function (child) {
// call child.map with the same callback
child.mapInPlace( callback );
});
};

/**
Expand Down

0 comments on commit d90452b

Please sign in to comment.