javascriptvector

Element-wise Operations In Javascript


I'm doing some physics simulations which of course involve vectors. This has become very difficult for me because to the best of my knowledge javascript doesn't support anything like this...

#with the aid of numpy
>>> a = np.array([1,2,3])
>>> b = np.array([9,2,7])
>>> a+b
array([10,  4, 10])

I've been able to work around this limitation by defining functions that will achieve the same thing, but my formulas end up looking like this:

add(x, add( mult(v,dt), mult(mult( a(x), .5), Math.pow(dt,2))))

So my question is whether there are better ways to achieve this functionality, whether they be features of the language I am unaware of, libraries that address this issue, or more effective ways to deal with it.

Thanks for the help all.


Solution

  • 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 :)