feat: add configurable wind units
This commit is contained in:
@@ -11,8 +11,17 @@ import type {
|
||||
import { translate, type Language } from "@/lib/i18n";
|
||||
import { getProvinceFromTeryt, normalizeProvinceName } from "@/lib/provinces";
|
||||
import type { CurrentWeatherCondition } from "@/types/imgw-current";
|
||||
import type { WindSpeedUnit } from "@/types/units";
|
||||
|
||||
const locales: Record<Language, string> = { pl: "pl-PL", en: "en-GB" };
|
||||
export const DEFAULT_WIND_SPEED_UNIT: WindSpeedUnit = "ms";
|
||||
export const WIND_SPEED_UNITS: WindSpeedUnit[] = ["ms", "kmh", "mph"];
|
||||
|
||||
const windSpeedUnitLabels: Record<WindSpeedUnit, string> = {
|
||||
ms: "m/s",
|
||||
kmh: "km/h",
|
||||
mph: "mph",
|
||||
};
|
||||
|
||||
export function toNumber(value: unknown): number | null {
|
||||
if (typeof value === "number") return Number.isFinite(value) ? value : null;
|
||||
@@ -108,10 +117,35 @@ export function formatHumidity(value: number | null, language: Language = "pl")
|
||||
return value === null ? translate(language, "common.noData") : `${Math.round(value)}%`;
|
||||
}
|
||||
|
||||
export function formatWind(speed: number | null, direction?: number | null, language: Language = "pl") {
|
||||
export function isWindSpeedUnit(value: unknown): value is WindSpeedUnit {
|
||||
return typeof value === "string" && WIND_SPEED_UNITS.includes(value as WindSpeedUnit);
|
||||
}
|
||||
|
||||
export function getWindSpeedUnitLabel(unit: WindSpeedUnit) {
|
||||
return windSpeedUnitLabels[unit];
|
||||
}
|
||||
|
||||
export function convertWindSpeed(speed: number, unit: WindSpeedUnit) {
|
||||
if (unit === "kmh") return speed * 3.6;
|
||||
if (unit === "mph") return speed * 2.2369362921;
|
||||
return speed;
|
||||
}
|
||||
|
||||
export function formatWindSpeed(speed: number | null, language: Language = "pl", unit: WindSpeedUnit = DEFAULT_WIND_SPEED_UNIT) {
|
||||
if (speed === null) return translate(language, "common.noData");
|
||||
const convertedSpeed = convertWindSpeed(speed, unit);
|
||||
const digits = unit === "ms" ? 1 : 0;
|
||||
const formattedSpeed = new Intl.NumberFormat(locales[language], {
|
||||
minimumFractionDigits: digits,
|
||||
maximumFractionDigits: digits,
|
||||
}).format(convertedSpeed);
|
||||
return `${formattedSpeed} ${getWindSpeedUnitLabel(unit)}`;
|
||||
}
|
||||
|
||||
export function formatWind(speed: number | null, direction?: number | null, language: Language = "pl", unit: WindSpeedUnit = DEFAULT_WIND_SPEED_UNIT) {
|
||||
if (speed === null) return translate(language, "common.noData");
|
||||
const directionLabel = direction === null || direction === undefined ? "" : ` ${getWindDirection(direction)}`;
|
||||
return `${speed.toFixed(1)} m/s${directionLabel}`;
|
||||
return `${formatWindSpeed(speed, language, unit)}${directionLabel}`;
|
||||
}
|
||||
|
||||
export function formatRainfall(value: number | null, language: Language = "pl") {
|
||||
|
||||
Reference in New Issue
Block a user