Factsheet
Videos
Perhaps it is simpler to extend javascript's native Array, so that there is no need for keeping around an extra Vector.arr property. Here is a simple implementation called for learning purposes that boils down to this, in modern JS:
class Vector extends Array {
// example methods
add(other) {
return this.map((e, i) => e + other[i]);
}
}
// example usage
let v = new Vector(1, 2, 3);
console.log(v.add(v));
This class inherits Array's constructor. Note passing in a single value creates an empty Array of that length and not a length 1 Array. Vector would require a super call in the constructor to inherit exotic Array behavior, such as having a special length property, but this shouldn't be needed for a math vector of fixed length.
You can include fancier constructor behavior here, such as being able to construct from an Array as input.
You need to wrap up your resulting array in a new Vector object:
function Vector(components) {
// TODO: Finish the Vector class.
this.arr = components;
this.add = add;
}
function add(aa) {
if(this.arr.length === aa.arr.length) {
var result=[];
for(var i=0; i<this.arr.length; i++) {
result.push(this.arr[i]+aa.arr[i]);
}
return new Vector(result);
} else {
return error;
}
}
I should note also that you may want to do further reading on creating JavaScript objects, in the area of creating methods (such as your add method) on the prototype of the Vector object. There are many good tutorials out there.
I'm trying to find a library that has all of these primitive types in it. You know, it has vectors, quaternions, matrix, etc.
Essentially imagine the P5 library minus all of the rendering. P5 has a massive bundle size so just using it for these parts isn't really an option.
What would you recommend?
