-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathnearVector.ts
84 lines (69 loc) · 1.88 KB
/
nearVector.ts
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
export default class GraphQLNearVector {
private certainty?: number;
private distance?: number;
private readonly source: any;
private vector?: number[];
constructor(nearVectorObj: any) {
this.source = nearVectorObj;
}
toString(wrap = true) {
this.parse();
this.validate();
let args = [`vector:${JSON.stringify(this.vector)}`]; // vector must always be set
if (this.certainty) {
args = [...args, `certainty:${this.certainty}`];
}
if (this.distance) {
args = [...args, `distance:${this.distance}`];
}
if (!wrap) {
return `${args.join(",")}`;
}
return `{${args.join(",")}}`;
}
validate() {
if (!this.vector) {
throw new Error("nearVector filter: vector cannot be empty");
}
}
parse() {
for (let key in this.source) {
switch (key) {
case "vector":
this.parseVector(this.source[key]);
break;
case "certainty":
this.parseCertainty(this.source[key]);
break;
case "distance":
this.parseDistance(this.source[key]);
break;
default:
throw new Error("nearVector filter: unrecognized key '" + key + "'");
}
}
}
parseVector(vector: any[]) {
if (!Array.isArray(vector)) {
throw new Error("nearVector filter: vector must be an array");
}
vector.forEach((elem: any) => {
if (typeof elem !== "number") {
throw new Error("nearVector filter: vector elements must be a number");
}
});
this.vector = vector;
}
parseCertainty(cert: number) {
if (typeof cert !== "number") {
throw new Error("nearVector filter: certainty must be a number");
}
this.certainty = cert;
}
parseDistance(dist: number) {
if (typeof dist !== "number") {
throw new Error("nearVector filter: distance must be a number");
}
this.distance = dist;
}
}