Last active
January 20, 2017 18:20
-
-
Save vsemozhetbyt/3b225c62f226e8d71156c6029ce298eb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /******************************************************************************/ | |
| 'use strict'; | |
| /******************************************************************************/ | |
| // progress bar as a module | |
| module.exports = function pb(edge = 0) { | |
| const rl = require('readline'); | |
| const DEFAULT_FREQ = 500; | |
| const HUNDRED_PERCENT = 100; | |
| const PB_LENGTH = 50; | |
| const PB_SCALE = HUNDRED_PERCENT / PB_LENGTH; | |
| const NANOSECONDS_PER_SECOND = 1e9; | |
| const hrStart = process.hrtime(); | |
| function clearLine() { | |
| rl.cursorTo(process.stdout, 0); | |
| rl.clearLine(process.stdout, 0); | |
| } | |
| function getTimePast() { | |
| const hrEnd = process.hrtime(hrStart); | |
| return `${ | |
| ((hrEnd[0] * NANOSECONDS_PER_SECOND + hrEnd[1]) / NANOSECONDS_PER_SECOND).toFixed(1) | |
| } s`; | |
| } | |
| return { | |
| edge, | |
| stat: 0, | |
| start(freq = DEFAULT_FREQ) { | |
| this.updater = setInterval(() => { this.update(); }, freq); | |
| }, | |
| update(stat = this.stat) { | |
| const statPercent = | |
| stat === this.edge || stat > this.edge ? | |
| HUNDRED_PERCENT : | |
| stat / this.edge * HUNDRED_PERCENT; | |
| const barsNumber = Math.floor(statPercent / PB_SCALE); | |
| const padsNumber = PB_LENGTH - barsNumber; | |
| clearLine(); | |
| process.stdout.write( | |
| `${'█'.repeat(barsNumber)}${'░'.repeat(padsNumber)} ${statPercent.toFixed(1)}% ${getTimePast()} (${stat.toLocaleString()} of ${this.edge.toLocaleString()})` | |
| ); | |
| }, | |
| end() { | |
| clearInterval(this.updater); | |
| this.stat = this.edge; | |
| this.update(); | |
| console.log('\n'); | |
| }, | |
| clear() { | |
| clearInterval(this.updater); | |
| clearLine(); | |
| }, | |
| }; | |
| }; | |
| /******************************************************************************/ |
Author
vsemozhetbyt
commented
Jan 20, 2017

Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment