blob: 64b50e196d2878ac90a579836753cc00031db503 [file] [log] [blame]
daniel.teske70445a72018-10-05 09:15:42 +02001class ProgressStats {
2
3 constructor(totalDownloads) {
4 this.totalDownloads = totalDownloads
5 this.downloadCounter = 0
6 this.timestamps = []
7 }
8
9 logNext() {
10 this.downloadCounter++
11 this.timestamps.push({
12 "index": this.downloadCounter,
13 "timestamp": Date.now()
14 })
15 }
16
17 /**
18 * calculates the percentage of finished downloads
19 * @returns {string}
20 */
21 getPercentage() {
22 var current = (this.downloadCounter / this.totalDownloads)
23 return Math.round(current * 1000.0) / 10.0
24 }
25
26 /**
27 * calculates the time left and outputs it in human readable format
28 * calculation is based on a reference length, that can be defined.
29 *
30 * @returns {string}
31 */
32 getTimeLeft(referenceLength) {
33 if(this.downloadCounter <= referenceLength){
34 //number of reference downloads must exist before left time can be predicted
35 return "? minutes"
36 }
37 var processDurationInSeconds = (Date.now() - this.timestamps[0].timestamp) / 1000
38 if(processDurationInSeconds < 60){
39 //process must run longer than 60seconds before left time can be predicted
40 return "? minutes"
41 }
42
43 var indexOfStepsBefore = this.timestamps.findIndex((t) => {
44 return t.index == (this.downloadCounter - referenceLength)
45 })
46 var lastSteps = this.timestamps[indexOfStepsBefore];
47 var millisOflastSteps = Date.now() - lastSteps.timestamp
48 var downloadsLeft = this.totalDownloads - this.downloadCounter
49 var millisecondsLeft = (millisOflastSteps / referenceLength) * downloadsLeft
50 return this.formatMilliseconds(millisecondsLeft)
51 }
52
53 /**
54 * inspired from https://stackoverflow.com/questions/19700283/how-to-convert-time-milliseconds-to-hours-min-sec-format-in-javascript
55 * @param millisec
56 * @returns {string}
57 */
58 formatMilliseconds(millisec) {
59 var seconds = (millisec / 1000).toFixed(1);
60 var minutes = (millisec / (1000 * 60)).toFixed(1);
61 var hours = (millisec / (1000 * 60 * 60)).toFixed(1);
62 var days = (millisec / (1000 * 60 * 60 * 24)).toFixed(1);
63 if (seconds < 60) {
64 return seconds + " seconds";
65 } else if (minutes < 60) {
66 return minutes + " minutes";
67 } else if (hours < 24) {
68 return hours + " hours";
69 } else {
70 return days + " days"
71 }
72 }
73
74}
75
76module.exports = ProgressStats