1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-11-22 16:43:46 +01:00
CodeWars/5kyu/vector_class/solution.js

55 lines
1.3 KiB
JavaScript
Raw Normal View History

class Vector {
constructor(array) {
this.values = array.slice(0);
}
mathOperation(vector, f) {
if (!vector || !(vector instanceof Vector) || this.values.length !== vector.values.length) {
throw "invalid operation";
}
let result = [];
for (let i = 0; i < this.values.length; i++) {
result.push(f(this.values[i], vector.values[i]));
}
return new Vector(result);
}
add(vector) {
return this.mathOperation(vector, (t, o) => t + o);
}
subtract(vector) {
return this.mathOperation(vector, (t, o) => t - o);
}
dot(vector) {
return this.mathOperation(vector, (t, o) => t * o)
.values.reduce((t, e) => t + e, 0);
}
norm() {
return Math.sqrt(this.dot(this));
}
toString() {
return `(${this.values.join(',')})`;
}
equals(other) {
if (!other || !(other instanceof Vector) || this.values.length !== other.values.length) {
return false;
} else if (other === this) {
return true;
} else {
for (let i = 0; i < this.values.length; i++) {
if (this.values[i] !== other.values[i]) {
return false;
}
}
return true;
}
}
}