-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathformat.ts
40 lines (32 loc) · 1.09 KB
/
format.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
export function formatCost(value: number | undefined, precision = 4) {
if (value == null) {
return '?';
}
return `$${value.toFixed(precision)}`;
}
/**
* Formats a token count to a human-readable string. Uses units like K, M, to improve readability.
*/
export function formatTokenCount(tokenCount: number, roundTo = 1) {
const roundedCount = Math.round(tokenCount / roundTo) * roundTo;
if (roundedCount === 0) {
return '0';
}
const suffixes = ['', 'K', 'M'];
// Pick suffix based on the order of magnitude of the count.
const suffixIndex = Math.min(
Math.floor(Math.log10(Math.abs(roundedCount)) / 3),
suffixes.length - 1,
);
const scaledCount = roundedCount / Math.pow(10, suffixIndex * 3);
return `${scaledCount.toFixed(0)}${suffixes[suffixIndex]}`;
}
export function formatTime(timeInMs: number) {
return `${(timeInMs / 1000).toFixed(1)} s`;
}
export function formatSpeed(tokens: number, timeInMs: number) {
if (tokens == null || timeInMs == null || timeInMs === 0) {
return '? tokens/s';
}
return `${((tokens * 1000) / timeInMs).toFixed(1)} tok/s`;
}