Base62 Encoding for Compact Identifiers

Encode non-negative integers as short Base62 strings and decode them back with BigInt, rejecting invalid input.

TypescriptData Integrity

Code

snippet
const ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const BASE = 62n;

export function encodeBase62(value: bigint | number): string {
  if (typeof value !== "bigint" && typeof value !== "number") {
    throw new TypeError("value must be a bigint or integer number");
  }
  if (typeof value === "number" && !Number.isInteger(value)) {
    throw new TypeError("number input must be an integer");
  }
  let remaining = typeof value === "number" ? BigInt(value) : value;
  if (remaining < 0n) throw new RangeError("value must be non-negative");
  if (remaining === 0n) return "0";
  let output = "";
  while (remaining > 0n) {
    output = ALPHABET[Number(remaining % BASE)] + output;
    remaining /= BASE;
  }
  return output;
}

export function decodeBase62(input: string): bigint {
  if (typeof input !== "string" || input.length === 0) {
    throw new TypeError("input must be a non-empty string");
  }
  let result = 0n;
  for (const char of input) {
    const index = ALPHABET.indexOf(char);
    if (index === -1) throw new RangeError("invalid base62 character: " + char);
    result = result * BASE + BigInt(index);
  }
  return result;
}