From 5c4e9b18db3f61634cc12b7b637c75ac5b6c50ba Mon Sep 17 00:00:00 2001 From: PunGrumpy <108584943+PunGrumpy@users.noreply.github.com> Date: Thu, 30 May 2024 09:54:06 +0700 Subject: [PATCH] refactor(duration): add current time calculation as a separate var Use decimalPlaces property in timeUnits array for better formatting --- src/utils/duration.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/utils/duration.ts b/src/utils/duration.ts index 993cbb6..d4da179 100644 --- a/src/utils/duration.ts +++ b/src/utils/duration.ts @@ -9,17 +9,18 @@ import chalk from 'chalk' * @returns {string} A formatted duration string including the time unit. */ function durationString(beforeTime: bigint): string { - const nanoseconds = Number(process.hrtime.bigint() - beforeTime) + const currentTime = process.hrtime.bigint() + const nanoseconds = Number(currentTime - beforeTime) const timeUnits = [ - { unit: 's', threshold: 1e9 }, - { unit: 'ms', threshold: 1e6 }, - { unit: 'µs', threshold: 1e3 } + { unit: 's', threshold: 1e9, decimalPlaces: 2 }, + { unit: 'ms', threshold: 1e6, decimalPlaces: 0 }, + { unit: 'µs', threshold: 1e3, decimalPlaces: 0 } ] - for (const { unit, threshold } of timeUnits) { + for (const { unit, threshold, decimalPlaces } of timeUnits) { if (nanoseconds >= threshold) { - const value = (nanoseconds / threshold).toFixed(threshold === 1e9 ? 2 : 0) + const value = (nanoseconds / threshold).toFixed(decimalPlaces) return formatTime(value, unit) } }