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]
-
1You 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.user395760– user3957602012年03月31日 12:41:43 +00:00Commented Mar 31, 2012 at 12:41
3 Answers 3
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.
Comments
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
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:
- The initial value of the result array should be dynamic
- I haven't tested the code if the arrays aren't of equal length
Good luck!