Skip to content

Instantly share code, notes, and snippets.

@hjzheng
Created April 20, 2020 06:24
Show Gist options
  • Save hjzheng/fe0224d51a40983ba5a16f31632d52d6 to your computer and use it in GitHub Desktop.
Save hjzheng/fe0224d51a40983ba5a16f31632d52d6 to your computer and use it in GitHub Desktop.

Revisions

  1. hjzheng created this gist Apr 20, 2020.
    36 changes: 36 additions & 0 deletions base58.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    function base58(encodeMap) {
    function base58encode(int64: string): string {
    let num = BigInt(int64)
    const base = 58n

    let res = ''
    while (num >= base) {
    res += encodeMap[num % base]
    num = num / base
    }
    res += encodeMap[num]
    return res
    .split('')
    .reverse()
    .join('')
    }

    /**
    * base58 to int64
    * @param {string} base58
    * @returns {string} int64
    */
    function base58decode(base58: string): string {
    let num = 0n
    for (let i = 0; i < base58.length; i++) {
    num = num * 58n + BigInt(encodeMap.indexOf(base58[i]))
    }
    return num.toString()
    }
    return {
    encode: base58encode,
    decode: base58decode,
    }
    }

    export default base58