Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* eslint-disable no-return-assign */
- const chalk = require('chalk');
- const ora = require('ora');
- const R = require('ramda');
- const prettyMs = require('pretty-ms');
- /**
- * Creates progress bar with appendable statuses.
- * @param {String} [title=''] Top title of the bar.
- * @param {String} [fillChar=chalk.cyan('-')] Filling character.
- * @param {String} [bgChar=' '] Background character
- * @param {String} [startingChar=chalk.gray('[')] [description]
- * @param {String} [endingChar=chalk.gray(']')] [description]
- * @param {Number} [total=10] Aka length of the bar.
- * @returns {Object} With tick and append functions.
- */
- const createProgressBar = ({
- title = '',
- fillChar = chalk.cyan('-'),
- bgChar = ' ',
- startingChar = chalk.gray('['),
- endingChar = chalk.gray(']'),
- total = 10,
- }) => {
- const MAX_SCREEN_LENGTH = 10;
- const barLength = total > MAX_SCREEN_LENGTH ? MAX_SCREEN_LENGTH : total;
- const getCompleteness = progress => Math.round((barLength * progress) / total);
- let currentProgress = 0;
- const fillProgress = () => fillChar.repeat(getCompleteness(currentProgress));
- const fillSpace = () => bgChar.repeat(barLength - getCompleteness(currentProgress));
- const spinner = ora();
- // mutation of spinner text causes it to update
- const updateProgress = text => (spinner.text = text);
- const appendedLines = [];
- const executionTimes = [];
- let timeOfLastTick;
- return {
- tick() {
- let prependedHeader = '';
- // const normalizedProgress = getNormalizedProgress(currentProgress);
- // start the spinner on first tick
- if (currentProgress === 0) {
- spinner.start();
- } else {
- const [, nanoseconds] = process.hrtime(timeOfLastTick);
- const timeBetweenTwoTicksInMs = nanoseconds / 1e6;
- executionTimes.push(timeBetweenTwoTicksInMs);
- const mean = R.mean(executionTimes);
- const roundMeanStr = `${Math.round(mean)}ms`;
- const estTimeLeftStr = prettyMs(Math.round((mean * (total - currentProgress)) / 1000));
- prependedHeader = chalk.grey(
- `Avg exec time: ${chalk.white(roundMeanStr)}, est. time left: ` +
- `${chalk.white(estTimeLeftStr)}`,
- );
- }
- currentProgress += 1;
- if (currentProgress >= total) {
- if (spinner.isSpinning) {
- spinner.succeed(`${title} π`);
- }
- return;
- }
- const currentProgressFrame =
- `${title}\n` +
- `${currentProgress}/${total} ${startingChar}` +
- `${fillProgress()}${fillSpace()}${endingChar}\n` +
- `${prependedHeader ? `\n${prependedHeader}\n` : ''}` +
- `\n${appendedLines.join('\n')}`;
- timeOfLastTick = process.hrtime();
- updateProgress(currentProgressFrame);
- },
- append(text) {
- appendedLines.push(text);
- },
- };
- };
- module.exports = createProgressBar;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement