From b4c3c51dc874711febf43b719ca878436b31084d Mon Sep 17 00:00:00 2001 From: Chocobozzz Date: Fri, 14 Aug 2020 17:28:54 +0200 Subject: Fix circular dependencies --- client/src/root-helpers/bytes.ts | 31 +++++++++++++++++++++++++++++++ client/src/root-helpers/index.ts | 1 + 2 files changed, 32 insertions(+) create mode 100644 client/src/root-helpers/bytes.ts (limited to 'client/src/root-helpers') diff --git a/client/src/root-helpers/bytes.ts b/client/src/root-helpers/bytes.ts new file mode 100644 index 000000000..ec8b55faa --- /dev/null +++ b/client/src/root-helpers/bytes.ts @@ -0,0 +1,31 @@ +const dictionary: Array<{ max: number; type: string }> = [ + { max: 1024, type: 'B' }, + { max: 1048576, type: 'KB' }, + { max: 1073741824, type: 'MB' }, + { max: 1.0995116e12, type: 'GB' } +] + +function getBytes (value: number, precision?: number | undefined): string | number { + const format = dictionary.find(d => value < d.max) || dictionary[dictionary.length - 1] + const calc = value / (format.max / 1024) + + const num = precision === undefined + ? calc + : applyPrecision(calc, precision) + + return `${num} ${format.type}` +} + +function applyPrecision (num: number, precision: number) { + if (precision <= 0) { + return Math.round(num) + } + + const tho = 10 ** precision + + return Math.round(num * tho) / tho +} + +export { + getBytes +} diff --git a/client/src/root-helpers/index.ts b/client/src/root-helpers/index.ts index 59468b31c..036a7677d 100644 --- a/client/src/root-helpers/index.ts +++ b/client/src/root-helpers/index.ts @@ -1,3 +1,4 @@ export * from './users' +export * from './bytes' export * from './peertube-web-storage' export * from './utils' -- cgit v1.2.3