Operator Overloading

Anupama H

@anuhosad

Operator Overloading

var p1 = new Point(4, 12);
var p2 = new Point(2, 4);

var addResult = new Point();
addResult.value = p1 + p2;

console.log("Addition : " + addResult.value); // "Addition : Point(6, 16)"

var subResult = new Point();
subResult.value = p1 - p2;

console.log("Subtraction : " + subResult.value); // "Subtraction : Point(2, 8)"

var mulResult = new Point();
mulResult.value = p1 * p2;

console.log("Multiplication : " + mulResult.value); // "Multiplication : Point(8, 48)"

var divideResult = new Point();
divideResult.value = p1 / p2;

console.log("Division : " + divideResult.value); // "Division : Point(2, 3)"

Complete Point Function: https://github.com/rauschma/op_overload

@anuhosad

Operator Overloading (contd...)

Tricks

  1. "+", "-", "*", "/" operators call operand.valueOf() function for object type operands
     
  2. Define setter function on value property of Point Prototype

 

@anuhosad

Operator Overloading (contd...)

function Point(x, y) {
  this.x = x;
  this.y = y;
  Point.operands = [];
};
Point.prototype.valueOf = function() {
  /* 
    smallest number for which + , - , * , / 
    operations give different values 
  */
  Point.operands.push(this);
  return 3;
}

@anuhosad

Point.prototype.toString = function (x, y) {
    return "Point(" + this.x + ", " + this.y + ")";
};

Operator Overloading (contd...)

@anuhosad

p1 + p2

p1.valueOf() + p2.valueOf()

var p1 = new Point(4, 12);
var p2 = new Point(2, 4);
var p3 = new Point();

p3.value = p1 + p2;

6

6

Point.operands = [p1, p2]

Operator Overloading (contd...)

Object.defineProperty(Point.prototype, "value", {
  set: function(value) {
    var l = Point.operands[0];
    var r = Point.operands[1];
    switch(value) {
      case 6: 
        /* 3 + 3 = addition */
        this.x = l.x + r.x;
        this.y = l.y + r.y;
        return this;
      case 0: 
        /* 3 - 3 = subtraction */
        this.x = l.x - r.x;
        this.y = l.y - r.y;
        return this;
      case 9: 
        /* 3 * 3 = multiplication */
        this.x = l.x * r.x;
        this.y = l.y * r.y;
        return this;
      case 1: 
        /* 3 / 3 = division */
        this.x = l.x / r.x;
        this.y = l.y / r.y;
        return this;
    }
  },
  get: function() {
    return this.toString();
  }
});

@anuhosad

References

@anuhosad

@anuhosad

Operator Overloading

By anupama hosad

Operator Overloading

  • 839