first commit
This commit is contained in:
81
frontend/src/lib/format.ts
Normal file
81
frontend/src/lib/format.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
export function formatValue(
|
||||
value: number | string | null | undefined,
|
||||
unit = "",
|
||||
precision = 2,
|
||||
locale = "pl-PL",
|
||||
): string {
|
||||
if (value === null || value === undefined || value === "") {
|
||||
return "--";
|
||||
}
|
||||
|
||||
if (typeof value === "number") {
|
||||
return `${value.toLocaleString(locale, {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: precision,
|
||||
})}${unit ? ` ${unit}` : ""}`;
|
||||
}
|
||||
|
||||
return unit ? `${value} ${unit}` : String(value);
|
||||
}
|
||||
|
||||
export function formatDateTime(value?: string | null, locale = "pl-PL"): string {
|
||||
if (!value) {
|
||||
return "--";
|
||||
}
|
||||
return new Date(value).toLocaleString(locale, {
|
||||
dateStyle: "short",
|
||||
timeStyle: "short",
|
||||
});
|
||||
}
|
||||
|
||||
export function formatDate(value?: string | null, locale = "pl-PL"): string {
|
||||
if (!value) {
|
||||
return "--";
|
||||
}
|
||||
const parsed = new Date(value);
|
||||
if (Number.isNaN(parsed.getTime())) {
|
||||
return value;
|
||||
}
|
||||
return parsed.toLocaleDateString(locale);
|
||||
}
|
||||
|
||||
export function formatShortTime(value?: string | null, locale = "pl-PL"): string {
|
||||
if (!value) {
|
||||
return "--";
|
||||
}
|
||||
return new Date(value).toLocaleTimeString(locale, {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
export function formatDurationShort(value?: number | null, locale = "pl-PL"): string {
|
||||
if (value === null || value === undefined || Number.isNaN(value)) {
|
||||
return "--";
|
||||
}
|
||||
|
||||
const totalSeconds = Math.max(Math.round(value), 0);
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
|
||||
if (locale.startsWith("pl")) {
|
||||
if (hours > 0) return `${hours}h ${minutes}m`;
|
||||
if (minutes > 0) return `${minutes}m ${seconds}s`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
|
||||
if (hours > 0) return `${hours}h ${minutes}m`;
|
||||
if (minutes > 0) return `${minutes}m ${seconds}s`;
|
||||
return `${seconds}s`;
|
||||
}
|
||||
|
||||
export function formatPercent(value?: number | null, precision = 1, locale = "pl-PL"): string {
|
||||
if (value === null || value === undefined || Number.isNaN(value)) {
|
||||
return "--";
|
||||
}
|
||||
return `${value.toLocaleString(locale, {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: precision,
|
||||
})}%`;
|
||||
}
|
||||
Reference in New Issue
Block a user