base91

This tag converts base91 data

Created by: hackvertor
Installed 1 times

Category: Convert

Created on: Thursday, October 10, 2024 at 11:55:09 AM

Updated on: Saturday, October 12, 2024 at 4:20:39 PM

This is a built in tag
Tag arguments
[]
Code
class base91 {
  encode(input) {
    const alphabet =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;<=>?@[]^_`{|}~"';
    let buffer = BigInt(
      "0x" +
        [...input]
          .map((c) => c.charCodeAt(0).toString(16).padStart(2, "0"))
          .join(""),
    );
    let encoded = "";
    while (buffer > 0) {
      const remainder = buffer % 91n;
      buffer = buffer / 91n;
      encoded = alphabet[Number(remainder)] + encoded;
    }
    return encoded;
  }

  decode(input) {
    const alphabet =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&()*+,./:;<=>?@[]^_`{|}~"';
    let buffer = BigInt(0);
    for (let char of input) {
      buffer = buffer * 91n + 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 base91Regex = /^[A-Za-z0-9!#$%&()*+,./:;<=>?@[\]^_`{|}~"]{10,}/;
    const result = base91Regex.exec(input);
    return result ? result : null;
  }
}