Skip to content

Instantly share code, notes, and snippets.

@tmarshall
Forked from inflammable/base58.js
Created May 10, 2020 02:28
Show Gist options
  • Save tmarshall/19530b133b120916e2b6d91d4aacd371 to your computer and use it in GitHub Desktop.
Save tmarshall/19530b133b120916e2b6d91d4aacd371 to your computer and use it in GitHub Desktop.
Base58 (and other) Encoding and Decoding in Javascript
/*
* (c) 2012 inflammable/raromachine
* Licensed under the MIT License.
* ---
* this is a refactored version of https://gist.github.com/inflammable/2929362
*/
const alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'
const base = alphabet.length
function encode(value) {
if (typeof value !== 'number') {
value = parseInt(value, 10)
if (Number.isNaN(value)) {
throw '.encode() expects an int'
}
}
let encoded = ''
while (value) {
const remainder = value % base
value = Math.floor(value / base)
encoded = alphabet[remainder].toString() + encoded
}
return encoded
}
function decode(str) {
if (typeof str !== 'string') {
throw '.decode() only accepts strings'
}
let decoded = 0
while(str) {
const alphabetPosition = alphabet.indexOf(str[0])
const power = str.length - 1
decoded += alphabetPosition * Math.pow(base, power)
str = str.substring(1)
}
return decoded
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment