eeprom/scripts/eepromv1a.js/bytefmt.js

46 lines
1.1 KiB
JavaScript

const EEPFMT = (() => {
const symbols = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y', 'R', 'Q'];
const format = (bytes, decimal) => {
if(bytes === 0)
return 'Zero Bytes';
const negative = bytes < 0;
const power = decimal ? 1000 : 1024;
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)
string += 'i';
string += 'B';
}
return string;
};
return {
format: format,
};
})();