Skip to content

Instantly share code, notes, and snippets.

@vsemozhetbyt
Last active January 20, 2017 18:21
Show Gist options
  • Save vsemozhetbyt/29dc6481e69050c3dded5afa95694b61 to your computer and use it in GitHub Desktop.
Save vsemozhetbyt/29dc6481e69050c3dded5afa95694b61 to your computer and use it in GitHub Desktop.
pbt.js
/******************************************************************************/
'use strict';
/******************************************************************************/
// title progress bar as a module
module.exports = function pbt(edge = 0) {
const savedTitle = process.title;
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 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;
process.title =
`${'█'.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${process.title}\n`);
},
clear() {
clearInterval(this.updater);
process.title = savedTitle;
},
};
};
/******************************************************************************/
@vsemozhetbyt
Copy link
Author

vsemozhetbyt commented Jan 20, 2017

@vsemozhetbyt
Copy link
Author

pbt

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