generated from 2BAD/ts-lib-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[ts] add utility function to convert sizes from human format
- Loading branch information
Showing
2 changed files
with
37 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
/** | ||
* Helper function to parse human-readable sizes | ||
* | ||
* @param size - The size string to parse. | ||
* @returns The parsed size in bytes. | ||
* @throws {Error} If the size string is invalid or cannot be parsed. | ||
*/ | ||
export const parseSize = (size: string): number => { | ||
const units: Record<string, number> = { | ||
b: 1, | ||
kb: 1024, | ||
mb: 1024 * 1024, | ||
gb: 1024 * 1024 * 1024 | ||
} | ||
const match = size.toLowerCase().match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/) | ||
|
||
if (!match || match.length < 2) { | ||
throw new Error('Invalid size format') | ||
} | ||
|
||
const value = Number.parseFloat(match[1] ?? '') | ||
if (Number.isNaN(value)) { | ||
throw new Error('Invalid numeric value') | ||
} | ||
|
||
const unit = match[2] ?? 'b' | ||
if (!(unit in units)) { | ||
throw new Error('Invalid unit') | ||
} | ||
|
||
return Math.floor(value * units[unit]) | ||
} |