Tree Map
by dimitrs_papadimitriou
HTML
<script src="https://rawgit.com/eu81273/jsfiddle-console/master/console.js"></script>
JavaScript
class Tree {}
class Leaf extends Tree {
constructor(value) {
super()
this.value = value;
}
map(f) {
return new Leaf(f(this.value));
}
show() {
return `Leaf(${this.value})` //for display purposes
}
}
class Node extends Tree {
constructor(left, v,right) {
super()
this.left = left;
this.v=v;
this.right = right;
}
map(f) {
return new Node(this.left.map(f), f(this.v),this.right.map(f));
}
show() {
return `(${this.left.show()},${this.v},${this.right.show()})`;
//for display purposes
}
}
var instance = new Node(new Node(new Leaf(7),3,new Leaf(3)),
6,
new Node(new Leaf(8),4,new Leaf(1)));
console.log(instance.show());
console.log(`after using map`);
console.log(instance.map(x=>x*x).show());