-
Notifications
You must be signed in to change notification settings - Fork 0
/
tree-map.js
62 lines (50 loc) · 1.57 KB
/
tree-map.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
*
* Implement a `map` method on this Tree class, using pseudoclassical instantiation.
*
* Map accepts a mapping function as its only argument. It traverses the tree,
* passing each node's value into the mapping function, and generates a new
* tree containing the results.
*
* So `map` should return a tree with the same structure, and different values,
* but it should NOT modify the tree that was passed in.
*
* Example:
* var root1 = new Tree(1);
* 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;
* })
* newTree.value // 2
* newTree.children[0].value // 4
* newTree.children[1].value // 6
* newTree.children[0].children[1].value // 10
* newTree.children[1].children[1].value // 14
* root1.value // still 1
*/
var Tree = function (value){
this.value = value;
this.branches = [];
}
Tree.prototype.addBranch = function(value){
var newBranch = new Tree(value);
this.branches.push(newBranch);
}
Tree.prototype.map = function(cb){
var newTree = new Tree(cb(this.value));
for(var i = 0; i < this.branches.length; i++){
newTree.branches.push(this.branches[i].map(cb));
}
return newTree;
}
//---Building the Trees---
var oldTree = new Tree(3);
oldTree.addBranch(5);
var youngTree = oldTree.map(function(value){
return value * 2;
})