-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Progress.js
53 lines (48 loc) · 1.37 KB
/
Progress.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
import speedometer from './speedometer';
export default class Progress {
constructor(length, emitDelay = 1000) {
this.length = parseInt(length, 10) || 0;
this.transferred = 0;
this.speed = 0;
this.streamSpeed = speedometer(this.speed || 5000);
this.initial = false;
this.emitDelay = emitDelay;
this.eventStart = 0;
this.percentage = 0;
}
getRemainingBytes() {
return parseInt(this.length, 10) - parseInt(this.transferred, 10);
}
getEta() {
return this.length >= this.transferred
? this.getRemainingBytes() / this.speed * 1000000000
: 0;
}
flow(chunk, onProgress) {
const chunkLength = chunk.length;
this.transferred += chunkLength;
this.speed = this.streamSpeed(chunkLength);
this.percentage = Math.round(this.transferred / this.length * 100);
if (!this.initial) {
this.eventStart = Date.now();
this.initial = true;
}
if (
this.length >= this.transferred ||
Date.now() - this.eventStart > this.emitDelay
) {
this.eventStart = Date.now();
const progress = {
total: this.length,
transferred: this.transferred,
speed: this.speed,
eta: this.getEta(),
};
if (this.length) {
progress.remaining = this.getRemainingBytes();
progress.percentage = this.percentage;
}
onProgress(progress);
}
}
}