Operator overloading, via Symbol.arithmetic?

# Alex Vincent (4 months ago)

Regarding operator overloading, I had a new idea last night.

Suppose we could express arithmetic operations on an object via a "well-defined" symbol (using the specification's terminology), named Symbol.arithmetic:

let a = new Fraction(1, 2); // 1/2 let b = new Complex(2, 5); // 2 + 5i

a * b: function() { let ta = (typeof a == "number") || (a instanceof Number); let tb = (typeof b == "number") || (b instanceof Number);

if (ta && tb) { // just do the regular operation, as defined in ES7, section 12.7.3 (yawn) } if (typeof a[Symbol.arithmetic] == "function") { return a[Symbol.arithmetic](a, "", b); } if (typeof b[Symbol.arithmetic] == "function") { return b[Symbol.arithmetic](a, "", b); } return NaN; }

This algorithm would be compatible, I think, with existing JavaScript: (new Object) * (new Object) == NaN right now. This supports the traditional arithmetic and comparison operators, and the new ** operator rather well.

For unary operators + and -, just make the first argument 0, and let the third argument be the object.

For the assignment operator, only run the left-hand assignment test, and perhaps treat it like a property definition (returning truthy means the operation succeeded, false means it failed).

I am well aware that this doesn't cover other operators, like []. This is just a starting suggestion.

# Igor Baklan (4 months ago)

previous discussion (FYI) operator-overloading-proposal