0

This is more of a "for fun" sort of thing, as it would be impractical to actually use this. I just want to satisfy my curiosity as to whether or not it's even possible.

I have a function...

function longAdd(a,b){
  //computation here
  return sum;
}

...which "adds" the values of a and b together as a string; meaning, it iterates through each character and adds them up. Thus, it can compute numbers which are greater than what could otherwise be achieved.

(for the purposes of this question, the actual code should not be relevant, so it is not included)

My question is: would it be possible to directly change the "+" operator to use this function? For instance,

c+d

anywhere in the code would essentially compute longAdd(c,d).

Any possible hacky ways to achieve this? For that matter, can the behavior of any operators be directly changed?

Note: Yes, I am aware this would screw up concatenation and big, numerical values would have to stay strings. This is just a concept I'm curious about.

dav
  • 375
  • 3
  • 18
  • @Quentin: Well...that's embarrassing... :-) I mean, I *wrote* the accepted answer there, you'd think I'd have a link handy and remember to use it. – T.J. Crowder Apr 12 '17 at 13:11
  • 2
    @T.J.Crowder — Yeah, it's disgraceful that you don't remember the details of all thirteen thousand answers you've written! – Quentin Apr 12 '17 at 13:17

1 Answers1

2

My question is: would it be possible to directly change the "+" operator to use this function?

No, JavaScript has no user-defined operator overloading at all.

The nearest I can see getting is defining an object with its own valueOf method which returns the result of converting itself to a string and doing your longAdd just on itself, and returning that result. Then the existing + would trigger that behavior on the objects referenced by a and b.

That's not overloading +, just taking advantage of the behavior it already has:

function Thing(val) {
    this.val = val;
}
Thing.prototype.valueOf = function() {
    // Here I'm just doubling it; you'd actually do your longAdd thing
    return this.val * 2;
};

var a = new Thing(1);
var b = new Thing(2);
console.log(a + b); // 6 (1 * 2 + 2 * 2)

Or with ES2015's class:

class Thing {
    constructor(val) {
      this.val = val;
    }
    valueOf() {
      return this.val * 2;
    }
}

const a = new Thing(1);
const b = new Thing(2);
console.log(a + b); // 6 (1 * 2 + 2 * 2)

Or just with objects, no constructors:

var thingPrototype = {
    valueOf: function() {
      return this.val * 2;
    }
};

var a = Object.create(thingPrototype);
a.val = 1;
var b = Object.create(thingPrototype);
b.val = 2;
console.log(a + b); // 6 (1 * 2 + 2 * 2)
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Aw, bummer...well, that's interesting about the valueOf, at any rate, thanks for the info. – dav Apr 12 '17 at 13:02