@js-data-tools/js-helpers
Version:
A set of JavaScript / TypeScript helper functions for parsing, converting, transforming and formatting data.
72 lines (71 loc) • 2.42 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.trackProgressAsync = exports.ProgressReporter = void 0;
class ProgressReporter {
constructor(logCallback, reportPeriodMsec) {
this.startTime = Date.now();
this.lastReportTime = this.startTime;
this.count = 0;
this.duration = 0;
this.reportEvery = reportPeriodMsec ?? 1000;
this.log = logCallback || ProgressReporter.defaultLog;
}
start() {
this.startTime = Date.now();
this.count = 0;
this.lastReportTime = this.startTime;
}
entry() {
++this.count;
if (this.reportEvery > 0 && Date.now() - this.lastReportTime >= this.reportEvery) {
this.duration = Date.now() - this.startTime;
this.report();
}
}
stop() {
if (this.startTime !== null) {
this.duration = Date.now() - this.startTime;
}
}
stopAndReport() {
this.stop();
this.report(true);
}
report(completed = false) {
const rate = this.count > 0 ? Math.floor((this.count * 1000) / this.duration) : 0;
this.log(this.duration, this.count, rate, completed);
this.lastReportTime = Date.now();
}
static logToConsole(duration, count, rate, completed) {
console.log(ProgressReporter.formatMessage(duration, count, rate));
}
static logToStdOut(duration, count, rate, completed) {
process.stdout.write(ProgressReporter.formatMessage(duration, count, rate) + (completed ? "\n" : "\r"));
}
static formatMessage(duration, count, rate) {
return `Duration: ${duration / 1000} seconds, count: ${count}, rate: ${rate} entries/second`;
}
}
ProgressReporter.defaultLog = process && process.stdout ? ProgressReporter.logToStdOut : ProgressReporter.logToConsole;
exports.ProgressReporter = ProgressReporter;
async function* trackProgressAsync(source, report) {
let reporter;
if (report) {
if (typeof report === "function") {
reporter = new ProgressReporter(report);
}
else {
reporter = report;
}
}
else {
reporter = new ProgressReporter();
}
reporter.start();
for await (const item of source) {
yield item;
reporter.entry();
}
reporter.stopAndReport();
}
exports.trackProgressAsync = trackProgressAsync;