-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathScanListener.js
More file actions
executable file
·53 lines (40 loc) · 1.11 KB
/
ScanListener.js
File metadata and controls
executable file
·53 lines (40 loc) · 1.11 KB
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
export default class ScanListener {
static triple(type, callback) {
return new ScanListener(type, callback).setAction();
}
static single(type, callback) {
return new ScanListener(type, callback);
}
constructor(type, callback, shouldCallback = () => true) {
this.callback = callback;
this.type = type;
this.shouldCallback = shouldCallback;
this.history = [];
}
setAction(minScans = 3, withinMilliseconds = 1000) {
this.shouldCallback = scan => {
const now = Date.now();
const scans = this.history.slice(-minScans).filter(historyScan => historyScan.rawBarcode === scan.rawBarcode && this.type.matches(historyScan.rawBarcode));
if (scans.length !== minScans) {
return false;
}
const oldest = scans[0];
const tooSlow = now - oldest.scannedAt.getTime() >= withinMilliseconds;
if (tooSlow) {
return false;
}
this.history = [];
return true;
}
return this;
}
handleScan(scan) {
if (this.type.matches(scan.rawBarcode)) {
this.history.push(scan);
if (!this.shouldCallback(scan)) {
return;
}
this.callback(this.type.get(scan.rawBarcode));
}
}
}