1
0
Fork 0
mirror of https://gitlab.com/mfocko/CodeWars.git synced 2024-09-16 20:56:57 +02:00
CodeWars/5kyu/vector_class/solution.js
Matej Focko fc899b0b02
chore: initial commit
Signed-off-by: Matej Focko <mfocko@redhat.com>
2021-12-28 16:19:58 +01:00

54 lines
1.3 KiB
JavaScript

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;
}
}
}