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