• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1class ProgressStats {
2  constructor (trackerName, totalTasks) {
3    this.trackerName = trackerName
4    this.totalTasks = totalTasks
5    this.taskCounter = 0
6  }
7
8  logNext () {
9    this.taskCounter++
10    if (!this.beginTime) {
11      this.beginTime = new Date()
12    }
13  }
14
15  /**
16     * Begin a new task.  Print the current progress and then increment the number of tasks.
17     * @param  {string}    A short message about the current task progress
18     * @param  {[boolean]} logTimeLeft whether or not to log the time left.
19     */
20  beginTask (message, logTimeLeft) {
21    this.printStats(message, logTimeLeft)
22    this.logNext()
23  }
24
25  /**
26     * Print the current progress.
27     * @param  {string}    A short message about the current task progress
28     * @param  {[boolean]} logTimeLeft whether or not to log the time left.
29     */
30  printStats (message, logTimeLeft) {
31    message = `${message}; ${this.trackerName} progress: ${this.getPercentage()}% done`
32    if (logTimeLeft) {
33      message = `${message} - ${this.getTimeLeft()} left`
34    }
35    console.log(message)
36  }
37
38  /**
39     * calculates the percentage of finished downloads
40     * @returns {string}
41     */
42  getPercentage () {
43    var current = (this.taskCounter / this.totalTasks)
44    return Math.round(current * 1000.0) / 10.0
45  }
46
47  /**
48     * calculates the time left and outputs it in human readable format
49     * calculation is based on the average time per task so far
50     *
51     * @returns {string}
52     */
53  getTimeLeft () {
54    if (this.taskCounter === 0) return '?'
55    const averageTimePerTask = (Date.now() - this.beginTime.getTime()) / this.taskCounter
56    var tasksLeft = this.totalTasks - this.taskCounter
57    var millisecondsLeft = averageTimePerTask * tasksLeft
58    return this.formatMilliseconds(millisecondsLeft)
59  }
60
61  /**
62     * inspired from https://stackoverflow.com/questions/19700283/how-to-convert-time-milliseconds-to-hours-min-sec-format-in-javascript
63     * @param millisec
64     * @returns {string}
65     */
66  formatMilliseconds (millisec) {
67    var seconds = (millisec / 1000).toFixed(1)
68    var minutes = (millisec / (1000 * 60)).toFixed(1)
69    var hours = (millisec / (1000 * 60 * 60)).toFixed(1)
70    var days = (millisec / (1000 * 60 * 60 * 24)).toFixed(1)
71    if (seconds < 60) {
72      return seconds + ' seconds'
73    } else if (minutes < 60) {
74      return minutes + ' minutes'
75    } else if (hours < 24) {
76      return hours + ' hours'
77    } else {
78      return days + ' days'
79    }
80  }
81}
82
83module.exports = ProgressStats
84