-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.js
More file actions
90 lines (74 loc) · 2.46 KB
/
tree.js
File metadata and controls
90 lines (74 loc) · 2.46 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
//(function(){
function Tree() {
this.tree_id = Math.floor(Math.random() * 100000);
}
Tree.prototype.size = function () {
if(this instanceof Leaf) return 1;
return (1 + this.left.size() + this.right.size());
}
Tree.prototype.maximum = function() {
if(this instanceof Leaf) return this.val;
return Math.max(this.left.maximum(), this.right.maximum());
}
Tree.prototype.map = function(f) {
if(this instanceof Leaf) return new Leaf(f(this.val));
return new Node(this.left, this.right);
}
Tree.prototype.fold = function(initial, combiner) {
if(this instanceof Leaf) return initial(this.val);
return combiner(this.left.fold(initial, combiner), this.right.fold(initial, combiner))
}
Tree.prototype.maximum_via_fold = function() {
var initial = function(x) {return(x)};
var combiner = function(l, r) {return(Math.max(l, r))};
return this.fold(initial, combiner);
}
Tree.prototype.size_via_fold = function() {
var initial = function() {return(1)};
var combiner = function(l, r) {return(1+l+r)};
return this.fold(initial, combiner);
}
Tree.prototype.map_via_fold = function(f) {
var initial = function(x) {return new Leaf(f(x))};
var combiner = function(l, r) {return new Node(l, r)};
return this.fold(initial, combiner);
}
Tree.prototype.to_array = function() {
function helper(arr, level, tree) {
arr[level] === undefined ? arr[level] = [tree] : arr[level].push(tree)
if(tree instanceof Node) {
helper(arr, level+1, tree.left)
helper(arr, level+1, tree.right)
}
return arr
}
return helper([], 0, this);
}
Tree.prototype.log = function() {
function helper(arr, str) {
if(arr.length == 0) return(str);
if(arr.length > 0) {
var level = arr.shift();
for(var i=0; i<arr.length; i++) {str = str + " "}
for(var i=0; i<level.length; i++) {
if(level[i] instanceof Leaf) {str = str + level[i].val} else {str = str + "*"};
str = str + " ";
}
return helper(arr, str + "\n\n")
}
}
console.log(helper(this.to_array(), ""));
}
function Leaf(val) {
Tree.call(this);
this.val = val;
}
function Node(left, right) {
Tree.call(this);
this.left = left;
this.right = right;
}
Leaf.prototype = Object.create(Tree.prototype);
Node.prototype = Object.create(Tree.prototype);
var tree = new Node(new Leaf(10), new Node(new Leaf(45), new Leaf(15)));
//})();