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;
  }
matchWith( pattern) {
        return  pattern.Leaf(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;
  }
   matchWith( pattern) {
        return  pattern.Node(this.left, this.v, this.right);
    }
 

  show() {
    return `(${this.left.show()},${this.v},${this.right.show()})`; 
    //for display purposes 
  }
}

Tree.prototype.map = function (f) {
    return this.matchWith({
        Leaf: v => new Leaf(f(v))   ,
        Node: (left, v, right) => {
            return new Node(left.map(f),f(v),right.map(f))
        }
    });
}
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());