-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformatBytes.js
32 lines (26 loc) · 1.02 KB
/
formatBytes.js
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
const flowRight = require('lodash.flowright');
const isFinite = require('lodash.isfinite');
const decimalPlaces = require('./decimalPlaces');
const prefixWith = require('./prefixWith');
const suffixWith = require('./suffixWith');
const unitConversion = require('./unitConversion');
module.exports = function formatBytes() {
return (numberArg) => {
const number = parseFloat(numberArg);
if (number == 0 || !isFinite(number)) {
return 0;
}
const absNumber = Math.abs(number);
const sign = number / absNumber;
const byteSuffixes = [' bytes', 'KB', 'MB', 'GB', 'TB', 'PB'];
let byteIndex = Math.floor(Math.log(absNumber) / Math.log(1024));
// cap byteIndex at array length
byteIndex = Math.min(byteIndex, byteSuffixes.length - 1);
return flowRight(
prefixWith(sign < 0 ? '-' : ''),
suffixWith(byteSuffixes[byteIndex]),
decimalPlaces(1),
unitConversion(1024, byteIndex)
)(absNumber);
};
}