Skip to content

Commit

Permalink
Merge pull request #160 from waifuvault/better-unit-for-total-size
Browse files Browse the repository at this point in the history
better file totalling
  • Loading branch information
VictoriqueMoe committed Jun 23, 2024
2 parents 46d51df + b2dc3df commit a6b0b5a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 14 deletions.
2 changes: 1 addition & 1 deletion src/services/socket/RecordInfoSocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export class RecordInfoSocket {
const size = (await this.repo.getTotalFileSize()) ?? 0;
return {
recordCount,
recordSize: ObjectUtils.sizeToHuman(size),
recordSize: ObjectUtils.humanFileSize(size, false, 2),
};
}
}
31 changes: 18 additions & 13 deletions src/utils/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,25 @@ export class ObjectUtils {
return matches && matches[0] ? parseInt(matches[0]) : 0;
}

public static sizeToHuman(value: number): string {
const sizeKB = Math.floor(value / 1024);
const sizeMB = Math.floor(sizeKB / 1024);
const sizeGB = Math.floor(sizeMB / 1024);
if (value < 1024) {
return `${value} B`;
}
if (sizeKB < 1024) {
return `${sizeKB} KB`;
}
if (sizeMB < 1024) {
return `${sizeMB} MB`;
public static humanFileSize(bytes: number, si = false, dp = 1): string {
const thresh = si ? 1000 : 1024;

if (Math.abs(bytes) < thresh) {
return bytes + " B";
}
return `${sizeGB} GB`;

const units = si
? ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
: ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
let u = -1;
const r = 10 ** dp;

do {
bytes /= thresh;
++u;
} while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1);

return bytes.toFixed(dp) + " " + units[u];
}

public static timeToHuman(value: number, timeUnit: TimeUnit = TimeUnit.milliseconds): string {
Expand Down

0 comments on commit a6b0b5a

Please sign in to comment.