Skip to content

Instantly share code, notes, and snippets.

@gynekolog
Created March 18, 2024 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gynekolog/5ea89f25d68fa477f971c683a4920f49 to your computer and use it in GitHub Desktop.
Save gynekolog/5ea89f25d68fa477f971c683a4920f49 to your computer and use it in GitHub Desktop.
Typescript To Convert Bytes To MB, KB, Etc
export function convertBytes(bytes: number, options: { useBinaryUnits?: boolean; decimals?: number } = {}): string {
const { useBinaryUnits = false, decimals = 2 } = options;
if (decimals < 0) {
throw new Error(`Invalid decimals ${decimals}`);
}
const base = useBinaryUnits ? 1024 : 1000;
const units = useBinaryUnits
? ["Bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
: ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"];
const i = Math.floor(Math.log(bytes) / Math.log(base));
return `${(bytes / Math.pow(base, i)).toFixed(decimals)} ${units[i]}`;
}
@gynekolog
Copy link
Author

gynekolog commented Mar 18, 2024

Test:

import { describe, expect } from "vitest";
import { convertBytes } from "./bytes";

describe("convertBytes", () => {
  const fileSizeInBytes = 2048;

  describe("default conversion", () => {
    it("should convert to KB", () => {
      const resultKB = convertBytes(fileSizeInBytes);
      expect(resultKB).toBe("2.05 KB");
    });

    it("should convert to MB", () => {
      const resultMB = convertBytes(fileSizeInBytes * 1000);
      expect(resultMB).toBe("2.05 MB");
    });

    it("should throw an error for invalid decimals", () => {
      expect(() => convertBytes(fileSizeInBytes, { decimals: -1 })).toThrowError("Invalid decimals -1");
    });
  });

  describe("conversion to binary units", () => {
    it("should convert to KiB", () => {
      const resultKiB = convertBytes(fileSizeInBytes, { useBinaryUnits: true });
      expect(resultKiB).toBe("2.00 KiB");
    });

    it("should convert to MiB", () => {
      const resultMiB = convertBytes(fileSizeInBytes * 1024, { useBinaryUnits: true });
      expect(resultMiB).toBe("2.00 MiB");
    });
  });

  it("should handle very large bytes (Number.MAX_SAFE_INTEGER)", () => {
    const result = convertBytes(Number.MAX_SAFE_INTEGER);
    expect(result).toBe("9.01 PB");
  });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment