-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathQueryProcess.ts
91 lines (81 loc) · 2.38 KB
/
QueryProcess.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
85
86
87
88
89
90
91
import { Matcher } from './Matcher';
import { Pattern } from './Pattern';
import { patternFactoryRegistry } from './patternFactoryRegistry';
import { QueryStrategyFactory } from './QueryStrategy';
const expectedTickTime = 1000 / 60;
const opsPerMeasure = 50;
export class QueryProcess {
public matcher: Matcher;
public sequence: Array<number>;
public predictions: Set<string> = new Set();
public totalSteps: number = 0;
public totalMatches: number = 0;
public totalTicks: number = 0;
public running: boolean = true;
public tick: () => void;
public constructor(
userInput: string,
onMatchCb: (pattern: Pattern, predictions: Array<number>) => void,
public onFinishCb: () => void,
) {
const sequence = this.sequence = userInput
.split(',')
.map(str => str.trim())
.filter(str => str !== '')
.map(str => +str)
.filter(num => !Number.isNaN(num));
if (sequence.length === 0) {
this.stop();
return;
}
this.matcher = new Matcher(patternFactoryRegistry);
const iterator = this.matcher.queryPattern(
sequence,
QueryStrategyFactory.createBasicStrategy(),
);
this.tick = () => {
if (!this.running) {
return;
}
const t0 = new Date().getTime();
const te = t0 + expectedTickTime;
while (new Date().getTime() < te) {
for (let i = 0; i < opsPerMeasure; i++) {
const iteratorResult = iterator.next();
if (iteratorResult.value !== undefined) {
const pattern = iteratorResult.value;
const predictions: Array<number> = [];
for (let j = 0; j < 10; j++) {
predictions.push(pattern.get(sequence.length + j));
}
const joined = predictions.join();
if (!this.predictions.has(joined)) {
this.predictions.add(joined);
this.totalMatches++;
onMatchCb(iteratorResult.value, predictions);
}
}
this.totalSteps++;
if (iteratorResult.done) {
this.stop();
return;
}
}
}
this.totalTicks++;
setTimeout(this.tick, 1);
};
this.start();
}
public start() {
this.running = true;
setTimeout(this.tick, 1);
}
public stop() {
const running = this.running;
this.running = false;
if (running) {
this.onFinishCb();
}
}
}