Skip to content

Commit 0e4a608

Browse files
committed
Added byteValueToHumanString
1 parent a636cc0 commit 0e4a608

2 files changed

Lines changed: 35 additions & 1 deletion

File tree

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "lup-utils",
3-
"version": "1.0.0",
3+
"version": "1.0.3",
44
"description": "NodeJS library providing utility functions.",
55
"main": "./lib/index",
66
"types": "./lib/index.d.ts",

src/string.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,37 @@
1+
/**
2+
* Converts a byte value to a human-readable string.
3+
*
4+
* @param bytes Value in bytes to convert to a human-readable string.
5+
* @param options Options for converting the string.
6+
* @returns Human-readable string representation of the byte value (e.g. )
7+
*/
8+
export function byteValueToHumanString(bytes: number, options?: {
9+
10+
/** Whether to use the decimal (base 1000) or the binary (base 1024) for conversion (default 1024). */
11+
decimalBase?: boolean;
12+
13+
/** If the label should be binary (e.g. "GiB" vs "GB") if decimalBase is false (default false). */
14+
binaryLabel?: boolean;
15+
16+
/** Number of decimal places to include (default 0). */
17+
precision?: number;
18+
19+
}): string {
20+
const units = (!options?.decimalBase && options?.binaryLabel)
21+
? ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']
22+
: ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
23+
const step = options?.decimalBase ? 1000 : 1024;
24+
let i = 0;
25+
let humanReadable = bytes;
26+
27+
while (humanReadable >= step && i < units.length - 1) {
28+
humanReadable /= step;
29+
i++;
30+
}
31+
32+
return humanReadable.toFixed(options?.precision ?? 0)+' '+units[i];
33+
}
34+
135
/**
236
* Parses a byte value from a string.
337
*

0 commit comments

Comments
 (0)