feat(new tools): Data Storage Units Converter and Data Transfer Rate Converter

New Tool: Data Transfer Rate Converter
New Tool: Data Storage Units Converter (with MB, MiB and Mb)

Fix #539 #785 #1160 #848

Data Storage Units Converter inspired by #948 by @utf26
This commit is contained in:
sharevb 2024-09-06 19:00:38 +02:00 committed by ShareVB
parent 87984e2081
commit 49aa769bb8
9 changed files with 522 additions and 1 deletions

View file

@ -0,0 +1,47 @@
export type BibytesUnits = 'iB' | 'KiB' | 'MiB' | 'GiB' | 'TiB' | 'PiB' | 'EiB' | 'ZiB' | 'YiB';
export type BytesUnits = 'B' | 'KB' | 'MB' | 'GB' | 'TB' | 'PB' | 'EB' | 'ZB' | 'YB';
export type BitsUnits = 'b' | 'Kb' | 'Mb' | 'Gb' | 'Tb' | 'Pb' | 'Eb' | 'Zb' | 'Yb';
export type AllSupportedUnits = BibytesUnits | BytesUnits | BitsUnits;
export function displayStorageAndRateUnits(
{ value, unit, precision = 3, appendUnit = false }:
{ value: number; unit: AllSupportedUnits; precision?: number ; appendUnit?: boolean }): string {
return value.toLocaleString(undefined, {
maximumFractionDigits: precision,
}) + (appendUnit ? unit : '');
}
export function convertStorageAndRateUnitsDisplay(
{ value, fromUnit, toUnit, precision = 3, appendUnit = false }:
{ value: number; fromUnit: AllSupportedUnits; toUnit: AllSupportedUnits; precision?: number; appendUnit?: boolean }): string {
return displayStorageAndRateUnits({
precision,
unit: toUnit,
appendUnit,
value: convertStorageAndRateUnits({
value, fromUnit, toUnit,
}),
});
}
export function convertStorageAndRateUnits(
{ value, fromUnit, toUnit }:
{ value: number; fromUnit: AllSupportedUnits; toUnit: AllSupportedUnits }): number {
const units = [
'iB', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB',
'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB',
'b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb',
];
const fromIndex = units.indexOf(fromUnit);
const fromFactor = fromIndex / 9 > 1 ? 1000 : 1024;
const fromDivisor = fromIndex / 9 > 2 ? 8 : 1;
const toIndex = units.indexOf(toUnit);
const toFactor = toIndex / 9 > 1 ? 1000 : 1024;
const toDivisor = toIndex / 9 > 2 ? 8 : 1;
const fromBase = (fromFactor ** (fromIndex % 9)) / fromDivisor;
const toBase = (toFactor ** (toIndex % 9)) / toDivisor;
return value * fromBase / toBase;
}