receptor/src/bitrate.js

60 lines
1.4 KiB
JavaScript
Raw Normal View History

2017-09-07 08:19:11 +02:00
export const Rates = {
2017-10-01 18:20:54 +02:00
"B/s": Math.pow(1024, 0),
2017-09-07 08:19:11 +02:00
"KiB/s": Math.pow(1024, 1),
"MiB/s": Math.pow(1024, 2),
"GiB/s": Math.pow(1024, 3),
"TiB/s": Math.pow(1024, 4),
};
export function convertToBitrate(value, unit) {
return value * Rates[unit];
}
2017-09-10 13:17:32 +02:00
export function convertFromBitrate(value, unit) {
return value / Rates[unit];
}
export function convertedRate(bitrate) {
2018-02-08 03:05:38 +01:00
if (bitrate > Rates["TiB/s"]) {
return [bitrate / Rates["TiB/s"], "TiB/s"];
} else if (bitrate > Rates["GiB/s"]) {
return [bitrate / Rates["GiB/s"], "GiB/s"];
2017-09-07 08:19:11 +02:00
} else if (bitrate > Rates["MiB/s"]) {
return [bitrate / Rates["MiB/s"], "MiB/s"];
2017-09-07 08:19:11 +02:00
} else if (bitrate > Rates["KiB/s"]) {
return [bitrate / Rates["KiB/s"], "KiB/s"];
2017-08-25 04:49:24 +02:00
} else {
return [bitrate, "B/s"];
}
}
function places(n) {
let places = 2;
if (n >= 100) {
places = 0;
} else if (n >= 10) {
places = 1;
}
if (n.toFixed(places) === (0).toFixed(places)) {
2017-12-29 08:07:40 +01:00
places = 0;
2017-08-25 04:49:24 +02:00
}
return places;
}
export function formatBitrate(bitrate) {
const [rate, unit] = convertedRate(bitrate);
return `${rate.toFixed(places(rate))} ${unit}`;
2017-08-25 04:49:24 +02:00
}
2017-09-10 14:21:08 +02:00
export function formatAmount(amount) {
const units = {
2018-02-08 03:05:38 +01:00
"TiB/s": "TiB",
"GiB/s": "GiB",
"MiB/s": "MiB",
"KiB/s": "KiB",
"B/s": "bytes"
};
const [rate, unit] = convertedRate(amount);
return `${rate.toFixed(places(rate))} ${units[unit]}`;
2017-09-10 14:21:08 +02:00
}