/ src / utils / file-size.ts
file-size.ts
 1  const ROUND_TO = 10;
 2  const SIZE_INCREMENT = 1000;
 3  const UNITS = ['byte', 'KB', 'MB', 'GB'];
 4  
 5  /**
 6   * Converts a byte count into a scaled value with a unit label (e.g. KB, MB, GB).
 7   *
 8   * @param {number} bytes - The number of bytes.
 9   * @returns {{ count: number, unit: string }} Scaled value and its corresponding unit.
10   */
11  export function getFileSizeParts(bytes: number) {
12      let index = 0;
13  
14      while (bytes >= SIZE_INCREMENT && index < UNITS.length - 1) {
15          bytes /= SIZE_INCREMENT;
16          index++;
17      }
18  
19      const count = Math.round(bytes * ROUND_TO) / ROUND_TO;
20      const unit = UNITS[index];
21  
22      return { count, unit };
23  }