Skip to content

Commit deea76c

Browse files
committed
utils: add readable bytes utility
1 parent c6708f3 commit deea76c

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/lib/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ export * from "./elements";
99
export * from "./forms";
1010
export * from "./api";
1111
export * from "./locale";
12+
export * from "./utils";

src/lib/utils/humanReadableBytes.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// This file is part of React-Invenio-Forms
2+
// Copyright (C) 2020 CERN.
3+
// Copyright (C) 2020 Northwestern University.
4+
// Copyright (C) 2022 TU Wien.
5+
//
6+
// React-Invenio-Forms is free software; you can redistribute it and/or modify it
7+
// under the terms of the MIT License; see LICENSE file for more details.
8+
9+
import _isNumber from "lodash/isNumber";
10+
11+
export function humanReadableBytes(bytes, decimalDisplay = false) {
12+
if (_isNumber(bytes)) {
13+
const base = decimalDisplay ? 1000 : 1024;
14+
const kiloBytes = base;
15+
const megaBytes = base * kiloBytes;
16+
const gigaBytes = base * megaBytes;
17+
18+
if (bytes < kiloBytes) {
19+
return `${bytes} bytes`;
20+
} else if (bytes < megaBytes) {
21+
return `${(bytes / kiloBytes).toFixed(2)} ${decimalDisplay ? "KB" : "KiB"}`;
22+
} else if (bytes < gigaBytes) {
23+
return `${(bytes / megaBytes).toFixed(2)} ${decimalDisplay ? "MB" : "MiB"}`;
24+
} else {
25+
return `${(bytes / gigaBytes).toFixed(2)} ${decimalDisplay ? "GB" : "GiB"}`;
26+
}
27+
}
28+
return "";
29+
}

src/lib/utils/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export { humanReadableBytes } from "./humanReadableBytes";

0 commit comments

Comments
 (0)