base58

This tag decodes and encodes base58

Created by: hackvertor
Installed 1 times

Category: Convert

Created on: Thursday, October 10, 2024 at 11:42:40 AM

Updated on: Thursday, October 10, 2024 at 11:42:40 AM

This is a built in tag
Tag arguments
[]
Code
class base58 {
  encode(input) {
    const alphabet =
      "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    let buffer = BigInt(
      "0x" +
        [...input]
          .map((c) => c.charCodeAt(0).toString(16).padStart(2, "0"))
          .join(""),
    );
    let encoded = "";
    while (buffer > 0) {
      const remainder = buffer % 58n;
      buffer = buffer / 58n;
      encoded = alphabet[Number(remainder)] + encoded;
    }
    return encoded;
  }

  decode(input) {
    const alphabet =
      "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
    let buffer = BigInt(0);
    for (let char of input) {
      buffer = buffer * 58n + BigInt(alphabet.indexOf(char));
    }
    const hex = buffer.toString(16);
    return (
      hex
        .match(/.{1,2}/g)
        ?.map((byte) => String.fromCharCode(parseInt(byte, 16)))
        .join("") ?? ""
    );
  }

  matches(input) {
    const base58Regex = /^[1-9A-HJ-NP-Za-km-z]{10,}$/;
    const result = base58Regex.exec(input);
    return result ? result : null;
  }
}