-
-
Save tmarshall/19530b133b120916e2b6d91d4aacd371 to your computer and use it in GitHub Desktop.
Base58 (and other) Encoding and Decoding in Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* (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