Improve some utils modules

Signed-off-by: Thomas Citharel <tcit@tcit.fr>
This commit is contained in:
Thomas Citharel 2022-08-29 16:52:18 +02:00
parent d43e7f2c34
commit b36ce27bbe
No known key found for this signature in database
GPG key ID: A061B9DDE0CA0773
2 changed files with 28 additions and 7 deletions

View file

@ -1,11 +1,9 @@
async function asyncForEach(
array: Array<any>,
// eslint-disable-next-line no-unused-vars
callback: (arg0: any, arg1: number, arg2: Array<any>) => void
): Promise<void> {
for (let index = 0; index < array.length; index += 1) {
// eslint-disable-next-line no-await-in-loop
await callback(array[index], index, array);
callback(array[index], index, array);
}
}

View file

@ -22,16 +22,39 @@ function localeShortWeekDayNames(): string[] {
}
// https://stackoverflow.com/a/18650828/10204399
function formatBytes(bytes: number, decimals = 2, zero = "0 Bytes"): string {
if (bytes === 0) return zero;
function formatBytes(
bytes: number,
decimals = 2,
locale: string | undefined = undefined
): string {
const formatNumber = (value = 0, unit = "byte") =>
new Intl.NumberFormat(locale, {
style: "unit",
unit,
unitDisplay: "long",
}).format(value);
if (bytes === 0) return formatNumber(0);
if (bytes < 0 || bytes > Number.MAX_SAFE_INTEGER) {
throw new RangeError(
"Number mustn't be negative and be inferior to Number.MAX_SAFE_INTEGER"
);
}
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const sizes = [
"byte",
"kilobyte",
"megabyte",
"gigabyte",
"terabyte",
"petabyte",
];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
return formatNumber(parseFloat((bytes / k ** i).toFixed(dm)), sizes[i]);
}
function roundToNearestMinute(date = new Date()) {