'A Vector Class in Javascript
I'm trying to implement a vector object instantiated like below...
var a = new Vector([1,2,3]);
var b = new Vector ([2,2,2]);
...and when I do a math operation I need something like this...
a.add(b); // should return Vector([3,4,5])
...but my code below returns me just an array
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 result;
} else {
return error;
}
}
Please help me out here. Thank you!
Solution 1:[1]
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.
Solution 2:[2]
The solution by James looks good but it's a bit old-fashioned in my opinion. Here is a way to solve the problem in modern ES6 Javascript Classes.
class Vector {
constructor(arr) {
this.arr = arr;
}
add(otherVector) {
const oa = otherVector.arr;
if (this.arr.length === oa.length) {
let res = []
for(let key in this.arr) {
res[key] = this.arr[key] + oa[key]
}
return new Vector(res)
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Eyk Rehbein |
