eeprom/scripts/eepromv1a.js/bytefmt.js

46 lines
1.1 KiB
JavaScript
Raw Normal View History

2024-02-02 21:00:24 +00:00
const EEPFMT = (() => {
const symbols = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'R', 'Q'];
const format = (bytes, decimal) => {
2024-02-02 21:00:24 +00:00
if(bytes === 0)
return 'Zero Bytes';
const negative = bytes < 0;
const power = decimal ? 1000 : 1024;
2024-02-02 21:00:24 +00:00
const exp = Math.floor(Math.log(bytes) / Math.log(power));
bytes = Math.abs(bytes);
const number = bytes / Math.pow(power, exp);
const symbol = symbols[exp];
let string = '';
if(negative)
string += '-';
const fractionDigits = bytes < power ? 0 : (number < 10 ? 2 : 1);
string += number.toLocaleString(undefined, {
maximumFractionDigits: fractionDigits,
minimumFractionDigits: fractionDigits,
});
string += ` ${symbol}`;
if(symbol === '') {
string += 'Byte';
if(number > 1)
string += 's';
} else {
if(!decimal)
2024-02-02 21:00:24 +00:00
string += 'i';
string += 'B';
}
return string;
};
return {
format: format,
};
})();