Skip to content

Commit b4e4057

Browse files
committed
Added byteValueToBitsHumanString
1 parent 0e4a608 commit b4e4057

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

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.3",
3+
"version": "1.0.4",
44
"description": "NodeJS library providing utility functions.",
55
"main": "./lib/index",
66
"types": "./lib/index.d.ts",

src/string.ts

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,29 @@
1+
/**
2+
* Converts a byte value to a human-readable string.
3+
* @param bytesPerSec Value in bytes per second to convert to a human-readable string.
4+
* @param options Options for converting the string.
5+
* @returns Human-readable string representation of the byte value as bits per second (e.g. "100 Mbps").
6+
*/
7+
export function byteValueToBitsHumanString(bytesPerSec: number, options?: {
8+
9+
/** Number of decimal places to include (default 0). */
10+
precision?: number,
11+
12+
}): string {
13+
const bits = bytesPerSec * 8;
14+
const base = 1000;
15+
const units = ['bits', 'Kbps', 'Mbps', 'Gbps', 'Tbps', 'Pbps'];
16+
let i = 0;
17+
let humanReadable = bits;
18+
19+
while (humanReadable >= base && i < units.length - 1) {
20+
humanReadable /= base;
21+
i++;
22+
}
23+
24+
return humanReadable.toFixed(options?.precision ?? 0) + ' ' + units[i];
25+
}
26+
127
/**
228
* Converts a byte value to a human-readable string.
329
*

0 commit comments

Comments
 (0)