From b36ce27bbe0accb773b41ebddc854c6ecb68aa44 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Mon, 29 Aug 2022 16:52:18 +0200 Subject: [PATCH] Improve some utils modules Signed-off-by: Thomas Citharel --- js/src/utils/asyncForEach.ts | 4 +--- js/src/utils/datetime.ts | 31 +++++++++++++++++++++++++++---- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/js/src/utils/asyncForEach.ts b/js/src/utils/asyncForEach.ts index f0f4ee97..ca3b9d27 100644 --- a/js/src/utils/asyncForEach.ts +++ b/js/src/utils/asyncForEach.ts @@ -1,11 +1,9 @@ async function asyncForEach( array: Array, - // eslint-disable-next-line no-unused-vars callback: (arg0: any, arg1: number, arg2: Array) => void ): Promise { 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); } } diff --git a/js/src/utils/datetime.ts b/js/src/utils/datetime.ts index 8988b7c8..ae490fb6 100644 --- a/js/src/utils/datetime.ts +++ b/js/src/utils/datetime.ts @@ -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()) {