Check out Sylvester. I think it might be what you are looking for.
But if you wanted to implement the objects yourself, then it might be better to do a more OOP approach. JavaScript is a prototype-based language, so it different a little bit from other OOP languages, but its still pretty easy to implement your own prototypes.
Something like:
Vector = function(items) {
this.items = items
}
Vector.prototype.add = function(other) {
var result = []
for(var i = 0; i < this.items; i++) {
result.push( this.items[i] + other.items[i])
}
return new Vector(result);
}
Vector.prototype.subtract = function(other) { /* code to subtract */ }
Vector.prototype.multiply = function(other) { /* code to multiply */ }
And then use them like this:
var a = new Vector([1,2,3]);
var b = new Vector([5,0,1]);
var result = a.add(b)
result.items // [6,2,4]
Or if you wanted to, you could also extend the Array class with some functions with
Array.prototype.vectorAdd = function(other) { /* code to add another array as a vector */ };
And call that using
[1,2,3].vectorAdd([5,0,1])
Hopefully, that might give you a starting point to make your code a little more readable.
Just another note: Unfortunately in this case, JavaScript doesn't support operation overloading so you can't do neat stuff like a+b
. You'll have to do something like a.add(b)
. but as long you return an appropriate object you can chain methods together. Like:
a.add(b).multiply(c).subtract(d);
ps. the presented code might be a little "off", I just typed it up off the top of my head, so treat it more like pseduocode :)