extract to src/utils as it doesn't assume the DOM

This commit is contained in:
Bruno Windels 2023-01-26 10:25:22 +01:00
parent a278086c37
commit 0f91f2065c
2 changed files with 38 additions and 37 deletions

View File

@ -16,15 +16,7 @@ limitations under the License.
import type { ITimeFormatter } from "../../types/types";
import {Clock} from "./Clock";
enum TimeScope {
Minute = 60 * 1000,
Day = 24 * 60 * 60 * 1000,
}
const MINUTES_IN_MS = 60 * 1000;
const HOURS_IN_MS = MINUTES_IN_MS * 60;
const DAYS_IN_MS = HOURS_IN_MS * 24;
import {formatDuration, TimeScope} from "../../../utils/timeFormatting";
export class TimeFormatter implements ITimeFormatter {
@ -81,34 +73,7 @@ export class TimeFormatter implements ITimeFormatter {
}
formatDuration(milliseconds: number): string {
let days = 0;
let hours = 0;
let minutes = 0;
if (milliseconds >= DAYS_IN_MS) {
days = Math.floor(milliseconds / DAYS_IN_MS);
milliseconds -= days * DAYS_IN_MS;
}
if (milliseconds >= HOURS_IN_MS) {
hours = Math.floor(milliseconds / HOURS_IN_MS);
milliseconds -= hours * HOURS_IN_MS;
}
if (milliseconds >= MINUTES_IN_MS) {
minutes = Math.floor(milliseconds / MINUTES_IN_MS);
milliseconds -= minutes * MINUTES_IN_MS;
}
const seconds = Math.floor(milliseconds / 1000);
let result = "";
if (days) {
result = `${days}d `;
}
if (hours || days) {
result += `${hours}h `;
}
if (minutes || hours || days) {
result += `${minutes}m `;
}
result += `${seconds}s`;
return result;
return formatDuration(milliseconds);
}
}

View File

@ -0,0 +1,36 @@
export enum TimeScope {
Minute = 60 * 1000,
Hours = 60 * TimeScope.Minute,
Day = 24 * TimeScope.Hours,
}
export function formatDuration(milliseconds: number): string {
let days = 0;
let hours = 0;
let minutes = 0;
if (milliseconds >= TimeScope.Day) {
days = Math.floor(milliseconds / TimeScope.Day);
milliseconds -= days * TimeScope.Day;
}
if (milliseconds >= TimeScope.Hours) {
hours = Math.floor(milliseconds / TimeScope.Hours);
milliseconds -= hours * TimeScope.Hours;
}
if (milliseconds >= TimeScope.Minute) {
minutes = Math.floor(milliseconds / TimeScope.Minute);
milliseconds -= minutes * TimeScope.Minute;
}
const seconds = Math.floor(milliseconds / 1000);
let result = "";
if (days) {
result = `${days}d `;
}
if (hours || days) {
result += `${hours}h `;
}
if (minutes || hours || days) {
result += `${minutes}m `;
}
result += `${seconds}s`;
return result;
}