aboutsummaryrefslogtreecommitdiff
path: root/src/zenserver/frontend/html/util/friendly.js
blob: 5d458616514d7fac8aaee377849a39bd843b47bd (plain) (blame)
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
33
34
35
36
37
38
39
40
41
42
43
44
// Copyright Epic Games, Inc. All Rights Reserved.

"use strict";

////////////////////////////////////////////////////////////////////////////////
export class Friendly
{
	static sep(value, prec=0)
	{
		return (+Number(value)).toLocaleString("en", {
			style: "decimal",
			minimumFractionDigits : prec,
			maximumFractionDigits : prec,
		});
	}

	static k(x, p=0)	{ return Friendly.sep((BigInt(x) + 999n)  / BigInt(Math.pow(10, 3))|0n, p) + "K"; }
	static m(x, p=1)	{ return Friendly.sep( BigInt(x)         / BigInt(Math.pow(10, 6)),   p) + "M"; }
	static g(x, p=2)	{ return Friendly.sep( BigInt(x)         / BigInt(Math.pow(10, 9)),   p) + "G"; }
	static kib(x, p=0)	{ return Friendly.sep((BigInt(x) + 1023n) / (1n << 10n)|0n, p) + " KiB"; }
	static mib(x, p=1)	{ return Friendly.sep( BigInt(x)         / (1n << 20n),   p) + " MiB"; }
	static gib(x, p=2)	{ return Friendly.sep( BigInt(x)         / (1n << 30n),   p) + " GiB"; }

	static duration(s)
	{
		const v = Number(s);
		if (v >= 1)		return Friendly.sep(v, 2) + " s";
		if (v >= 0.001)	return Friendly.sep(v * 1000, 2) + " ms";
		if (v >= 0.000001)	return Friendly.sep(v * 1000000, 1) + " µs";
		return Friendly.sep(v * 1000000000, 0) + " ns";
	}

	static bytes(x)
	{
		const v = BigInt(Math.trunc(Number(x)));
		if (v >= (1n << 60n))	return Friendly.sep(Number(v) / Number(1n << 60n), 2) + " EiB";
		if (v >= (1n << 50n))	return Friendly.sep(Number(v) / Number(1n << 50n), 2) + " PiB";
		if (v >= (1n << 40n))	return Friendly.sep(Number(v) / Number(1n << 40n), 2) + " TiB";
		if (v >= (1n << 30n))	return Friendly.sep(Number(v) / Number(1n << 30n), 2) + " GiB";
		if (v >= (1n << 20n))	return Friendly.sep(Number(v) / Number(1n << 20n), 1) + " MiB";
		if (v >= (1n << 10n))	return Friendly.sep(Number(v) / Number(1n << 10n), 0) + " KiB";
		return Friendly.sep(Number(v), 0) + " B";
	}
}