@hazae41/base58
Version:
Base58 for the web
34 lines (33 loc) • 1.26 kB
JavaScript
import { base16 } from "../../libs/base16/mod.js";
export var base58;
(function (base58) {
base58.alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
function encode(data) {
if (data.length === 0)
return "";
let zeros = 0;
while (zeros < data.length && data[zeros] === 0)
zeros++;
if (zeros === data.length)
return "1".repeat(zeros);
let result = "";
for (let value = BigInt(`0x${base16.encode(data)}`); value > 0n; value = value / 58n)
result = base58.alphabet[Number(value % 58n)] + result;
return "1".repeat(zeros) + result;
}
base58.encode = encode;
function decode(text) {
if (text.length === 0)
return new Uint8Array(0);
let zeros = 0;
while (zeros < text.length && text[zeros] === "1")
zeros++;
if (zeros === text.length)
return new Uint8Array(zeros);
let value = BigInt(0);
for (let i = zeros; i < text.length; i++)
value = (value * 58n) + BigInt(base58.alphabet.indexOf(text[i]));
return base16.decode("00".repeat(zeros) + value.toString(16));
}
base58.decode = decode;
})(base58 || (base58 = {}));