mirror of
https://github.com/iib0011/omni-tools.git
synced 2025-11-07 17:34:56 +05:30
Added Byte Converter utility (#279)
This commit is contained in:
parent
f3c5946e0d
commit
a1b13586cc
1 changed files with 26 additions and 0 deletions
26
src/tools/byteConverter.ts
Normal file
26
src/tools/byteConverter.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
/**
|
||||
* Byte Converter Utility
|
||||
* Converts between Bytes, KB, MB, GB, and TB
|
||||
*
|
||||
* Example:
|
||||
* convertBytes(1024, "KB", "MB") => 1
|
||||
*/
|
||||
|
||||
export type ByteUnit = "B" | "KB" | "MB" | "GB" | "TB";
|
||||
|
||||
export function convertBytes(value: number, fromUnit: ByteUnit, toUnit: ByteUnit): number {
|
||||
const units: ByteUnit[] = ["B", "KB", "MB", "GB", "TB"];
|
||||
|
||||
if (!units.includes(fromUnit) || !units.includes(toUnit)) {
|
||||
throw new Error(`Invalid unit. Use one of: ${units.join(", ")}`);
|
||||
}
|
||||
|
||||
const powerDifference = units.indexOf(toUnit) - units.indexOf(fromUnit);
|
||||
return value / Math.pow(1024, powerDifference);
|
||||
}
|
||||
|
||||
// Optional helper for quick conversions in CLI or UI
|
||||
export function formatConversion(value: number, fromUnit: ByteUnit, toUnit: ByteUnit): string {
|
||||
const result = convertBytes(value, fromUnit, toUnit);
|
||||
return `${value} ${fromUnit} = ${result} ${toUnit}`;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue