Files
clash-proxy/src/utils/parse-traffic.ts

15 lines
480 B
TypeScript
Raw Normal View History

2022-11-20 23:08:24 +08:00
const UNITS = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
2023-08-05 16:52:14 +08:00
const parseTraffic = (num?: number) => {
if (typeof num !== "number") return ["NaN", ""];
2022-11-20 23:08:24 +08:00
if (num < 1000) return [`${Math.round(num)}`, "B"];
2022-11-24 11:11:31 +08:00
const exp = Math.min(Math.floor(Math.log2(num) / 10), UNITS.length - 1);
2023-01-11 14:05:49 +08:00
const dat = num / Math.pow(1024, exp);
const ret = dat >= 1000 ? dat.toFixed(0) : dat.toPrecision(3);
2022-11-20 23:08:24 +08:00
const unit = UNITS[exp];
2021-12-08 23:36:34 +08:00
2022-11-20 23:08:24 +08:00
return [ret, unit];
2021-12-08 23:36:34 +08:00
};
export default parseTraffic;