UNPKG

basepura

Version:

Basepura encoder and decoder in TypeScript

61 lines (60 loc) 1.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.REGEX = exports.CHARS = void 0; exports.encode = encode; exports.decode = decode; exports.isBasepura = isBasepura; exports.CHARS = "BCDGHJKLNPQRSTWZbcdghjklnpqrstwz"; exports.REGEX = /^[BCDGHJKLNPQRSTWZbcdghjklnpqrstwz]+$/; const BASE = BigInt(exports.CHARS.length); /** * Encodes a non-negative bigint into a Basepura string. * * @param n - A non-negative bigint to encode * @returns A Basepura string representation of the input number * @throws {RangeError} If the input is negative */ function encode(n) { if (n < 0n) { throw new RangeError("Input must be a non-negative integer."); } if (n === 0n) { return exports.CHARS[0]; } let result = ""; while (n > 0n) { result = exports.CHARS[Number(n % BASE)] + result; n /= BASE; } return result; } /** * Decodes a Basepura string into a bigint. * * @param s - A Basepura string to decode * @returns The decoded bigint value * @throws {RangeError} If the input is empty or contains invalid characters */ function decode(s) { if (s.length === 0) { throw new RangeError("Input must not be empty."); } let result = 0n; for (let i = 0; i < s.length; i++) { const index = exports.CHARS.indexOf(s[i]); if (index < 0) { throw new RangeError("Invalid character in input."); } result = result * BASE + BigInt(index); } return result; } /** * Checks if a string is a valid Basepura string. * * @param s - A string to validate * @returns True if the string contains only valid Basepura characters, false otherwise */ function isBasepura(s) { return exports.REGEX.test(s); }