All files / rusted-chromium/log progress.ts

95.45% Statements 21/22
57.14% Branches 4/7
100% Functions 8/8
95.45% Lines 21/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77  4x     4x   4x   4x                 4x       13x 13x       19x 19x 19x       11x       11x       19x                   70x       11x               19x     19x 19x 19x   19x           4x  
/* eslint-disable-next-line import/no-namespace */
import * as chalk from 'chalk'
 
import type { ProgressConfig } from '../interfaces/interfaces'
import { Printer } from './printer'
 
export class ProgressBar extends Printer<ProgressBar> {
 
    private DEFAULT_CONFIG: Partial<ProgressConfig> = {
        barLength: 100,
        showNumeric: false,
        steps: 50,
    }
 
    private config: ProgressConfig | undefined
 
    public constructor(stdio: NodeJS.WriteStream) {
        super(stdio)
    }
 
    protected stop(): ProgressBar {
        this.config = undefined
        return this
    }
 
    private static calcNumeric(config: ProgressConfig, percent: number): string {
        const steps: number = config.steps as number
        const fracture = Math.round(percent * steps).toString().padStart(steps.toString().length, ' ')
        return `(${fracture}/${steps}${config.unit ? (' ' + config.unit) : ''})`
    }
 
    private setConfig(config: ProgressConfig): ProgressBar {
        this.config = {
            ...this.DEFAULT_CONFIG,
            ...config,
        }
        return this
    }
 
    private checkForComplete(config: ProgressConfig, percent: number): ProgressBar {
        return percent === 1
            ? this.clearLine()
                .deleteLastLine()
                .write(this.SUCCESS_FN(config.success))
                .stop()
                .newline()
            : this
    }
 
    protected self(): ProgressBar {
        return this
    }
 
    public start(config: ProgressConfig): ProgressBar {
        return this.stop()
            .setConfig(config)
            .write(config.start)
            .newline()
            .fraction(0)
    }
 
    public fraction(fraction: number): ProgressBar {
        Iif (!this.config) {
            return this
        }
        const barLength: number = this.config.barLength as number
        const doneAmount = Math.floor(barLength * fraction)
        const restAmount = barLength - doneAmount
 
        return this.clearLine()
            .write(`[${chalk.bgWhite(' ').repeat(doneAmount)}${chalk.grey('.').repeat(restAmount)}]${this.config.showNumeric ? ProgressBar.calcNumeric(this.config, fraction) : ''}`)
            .checkForComplete(this.config, fraction)
    }
}
 
export const progress = new ProgressBar(process.stdout)