5

Assuming points are represented using JavaScript Array as [x,y], how could I define the + operator on points such that:

[1,2] + [5,10] == [6,12]
1
  • 1
    You don't. Even if operator overloading was possible, and you could do it ad-hoc for existing types, you shouldn't because it breaks a lot of code. Commented Mar 31, 2012 at 12:41

3 Answers 3

6

JavaScript does not have a facility for overriding the built-in arithmetic operators.

There are some limited tricks you can pull by overriding the .valueOf() and .toString() methods, but I can't imagine how you could do what you're asking.

You could of course write a function to do it.

Sign up to request clarification or add additional context in comments.

Comments

2

How about a nice 'plus' method? This doesn't care how many indexes either array has, but any that are not numeric are converted to 0.

Array.prototype.plus= function(arr){
    var  L= Math.max(this.length,arr.length);
    while(L){
        this[--L]= (+this[L] || 0)+ (+arr[L] || 0);
    }
    return this;
};

[1, 2].plus([5, 10])

/*  returned value: (Array)
[6,12]
*/

[1, 2].plus([5, 10]).plus(['cat',10,5])

/*  returned value: (Array)
6,22,5
*/

Comments

0

I know that's not exactly what you want to do but a solution to your problem is to do something like that:

var arrayAdd = function() {
    var arrays = arguments,
        result = [0, 0];

    for( var i = 0, s = arrays.length; i < s; i++ ) {
        for( var j = 0, t = arrays[ i ].length; j < t; j++ ) {
            result[ j ] += parseInt( arrays[ i ].shift(), 10 );
        }
    }

    return result;
};

var sum = arrayAdd( [1,2], [5,10] ); //Should return [6, 12]

console.log( sum );

PLease note that this code is not final. I see some problems:

  1. The initial value of the result array should be dynamic
  2. I haven't tested the code if the arrays aren't of equal length

Good luck!

1 Comment

Hmm, according to your reputations @Misha, you must have thought about that solution already. :\

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.