-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
vector-class.js
68 lines (56 loc) · 1.73 KB
/
vector-class.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
class Vector {
constructor(components) {
this.components = components;
}
get length() {
return this.components.length;
}
add(vector) {
const func = (component, i) => component + vector.components[i];
const components = this.mapComponents(vector, func);
return new Vector(components);
}
subtract(vector) {
const func = (component, i) => component - vector.components[i];
const components = this.mapComponents(vector, func);
return new Vector(components);
}
dot(vector) {
const func = (component, i) => component * vector.components[i];
const components = this.mapComponents(vector, func);
return components.reduce((sum, component) => sum + component);
}
norm() {
return Math.sqrt(this.components.reduce((sum, component) => {
return sum + component * component;
}, 0));
}
equals(vector) {
return this.components.every((component, i) => component === vector.components[i]);
}
mapComponents(vector, func) {
if (vector.length != this.length)
throw new Error('Vectors must be the same length');
const components = this
.components
.map(func);
return components;
}
toString() {
return `(${this.components})`;
}
}
// const a = new Vector([1,2]);
// const b = new Vector([3,4]);
// console.log(a.add(b), new Vector([4,6]));
var a = new Vector([1, 2, 3]);
var b = new Vector([3, 4, 5]);
var c = new Vector([5, 6, 7, 8]);
console.log(a.add(b), new Vector([4, 6, 8]));
console.log(a.subtract(b), new Vector([-2, -2, -2]));
console.log(a.dot(b), 26);
// should return 1*3 + 2*4 + 3*5 = 26
console.log(a.norm(), Math.sqrt(14));
// should return sqrt(1^2 + 2^2 + 3^2) = sqrt(14)
// a.add(c); // throws an error
console.log(a.toString());