I have created a simple Vector class in JavaScript with a constructor and some methods. The add method returns a new Vector instance. When comparing the return value of the add method with a new instance declared with the same values false
is returned. I have also tried changing the equality operator to a double equals so I believe the issue is not to do with references.
class Vector {
constructor(components) {
this.length = components.length;
this.contents = components;
}
add(vector) {
if (this.length === vector.length) {
let a = [];
this.contents.forEach((cur, index) =>
a.push(cur + vector.contents[index])
);
return new Vector(a);
}
throw Error;
}
subtract(vector) {
if (this.length === vector.length) {
let a = [];
this.contents.forEach((cur, index) =>
a.push(cur - vector.contents[index])
);
return new Vector(a);
}
throw Error;
}
dot(vector) {
return this.contents.reduce(
(acc, cur, index) => (acc += cur * vector.contents[index]),
0
);
}
norm() {
return this.contents.reduce((acc, cur) => (acc += Math.pow(cur, 2)), 0);
}
equals(vector) {
return this.contents === vector;
}
toString() {
return this.contents.toString();
}
}
let a = new Vector([10, 20, 30]);
let b = new Vector([5, 15, 25]);
console.log(new Vector([15, 35, 55]));
console.log(a.add(b));
//Why does the log below return false?
console.log(new Vector([15, 35, 55]) === a.add(b));