2
0

feat:格式转换工具类

This commit is contained in:
zhongzm
2024-12-24 16:50:41 +08:00
parent 0939032e9b
commit f98fdf7e27

83
src/utils/units.ts Normal file
View File

@@ -0,0 +1,83 @@
// 带宽单位转换
export type BandwidthUnit = 'Kbps' | 'Mbps' | 'Gbps';
export const bandwidthUnits: BandwidthUnit[] = ['Kbps', 'Mbps', 'Gbps'];
export const bandwidthFactors: Record<BandwidthUnit, number> = {
Kbps: 1,
Mbps: 1000,
Gbps: 1000000
};
export function convertBandwidth(value: number, fromUnit: BandwidthUnit, toUnit: BandwidthUnit): number {
const fromFactor = bandwidthFactors[fromUnit];
const toFactor = bandwidthFactors[toUnit];
return (value * fromFactor) / toFactor;
}
export function formatBandwidth(kbpsValue: number): { value: number; unit: BandwidthUnit } {
if (kbpsValue >= 1000000) {
return { value: kbpsValue / 1000000, unit: 'Gbps' };
} else if (kbpsValue >= 1000) {
return { value: kbpsValue / 1000, unit: 'Mbps' };
}
return { value: kbpsValue, unit: 'Kbps' };
}
// 流量单位转换
export type StorageUnit = 'KB' | 'MB' | 'GB' | 'TB';
export const storageUnits: StorageUnit[] = ['KB', 'MB', 'GB', 'TB'];
export const storageFactors: Record<StorageUnit, number> = {
KB: 1,
MB: 1024,
GB: 1024 * 1024,
TB: 1024 * 1024 * 1024
};
export function convertStorage(value: number, fromUnit: StorageUnit, toUnit: StorageUnit): number {
const fromFactor = storageFactors[fromUnit];
const toFactor = storageFactors[toUnit];
return (value * fromFactor) / toFactor;
}
export function formatStorage(kbValue: number): { value: number; unit: StorageUnit } {
if (kbValue >= 1024 * 1024 * 1024) {
return { value: kbValue / (1024 * 1024 * 1024), unit: 'TB' };
} else if (kbValue >= 1024 * 1024) {
return { value: kbValue / (1024 * 1024), unit: 'GB' };
} else if (kbValue >= 1024) {
return { value: kbValue / 1024, unit: 'MB' };
}
return { value: kbValue, unit: 'KB' };
}
// 时间单位转换
export type TimeUnit = '秒' | '分钟' | '小时' | '天';
export const timeUnits: TimeUnit[] = ['秒', '分钟', '小时', '天'];
export const timeFactors: Record<TimeUnit, number> = {
'秒': 1,
'分钟': 60,
'小时': 3600,
'天': 86400
};
export function convertTime(value: number, fromUnit: TimeUnit, toUnit: TimeUnit): number {
const fromFactor = timeFactors[fromUnit];
const toFactor = timeFactors[toUnit];
return (value * fromFactor) / toFactor;
}
export function formatTime(secondsValue: number): { value: number; unit: TimeUnit } {
if (secondsValue >= 86400) {
return { value: secondsValue / 86400, unit: '天' };
} else if (secondsValue >= 3600) {
return { value: secondsValue / 3600, unit: '小时' };
} else if (secondsValue >= 60) {
return { value: secondsValue / 60, unit: '分钟' };
}
return { value: secondsValue, unit: '秒' };
}