refactor to vanilla js

This commit is contained in:
louisbuchbinder
2017-07-08 08:40:30 -07:00
parent 12ce0b0d69
commit 4ff09a0d77
13 changed files with 717 additions and 617 deletions

View File

@@ -1,26 +0,0 @@
class Base58Builder
constructor: ->
@alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
@base = @alphabet.length
encode: (num) ->
throw new Error('Value passed is not an integer.') unless /^\d+$/.test num
num = parseInt(num) unless typeof num == 'number'
str = ''
while num >= @base
mod = num % @base
str = @alphabet[mod] + str
num = (num - mod)/@base
@alphabet[num] + str
decode: (str) ->
num = 0
for char, index in str.split(//).reverse()
if (char_index = @alphabet.indexOf(char)) == -1
throw new Error('Value passed is not a valid Base58 string.')
num += char_index * Math.pow(@base, index)
num
# Export module
module.exports = new Base58Builder()

54
src/base58.js Normal file
View File

@@ -0,0 +1,54 @@
var alphabet = '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ';
var base = alphabet.length;
// Create a lookup table to fetch character index
var alphabetLookup = alphabet.split('').reduce(function (lookup, char, index) {
lookup[char] = index;
return lookup;
}, {});
function assertInteger(val) {
if (typeof val !== 'number' || isNaN(val) || Math.floor(val) !== val) {
throw new Error('Value passed is not an integer.');
}
}
function assertString(str) {
if (typeof str !== 'string') {
throw new Error('Value passed is not a string.');
}
}
function assertBase58Character(character) {
if (alphabetLookup[character] === undefined) {
throw new Error('Value passed is not a valid Base58 string.');
}
}
exports.encode = function (num) {
var str = '';
var modulus;
num = Number(num);
assertInteger(num);
while (num >= base) {
modulus = num % base;
str = alphabet[modulus] + str;
num = Math.floor(num / base);
}
return alphabet[num] + str;
};
exports.decode = function (str) {
assertString(str);
return str.split('').reverse().reduce(function (num, character, index) {
assertBase58Character(character);
return num + alphabetLookup[character] * Math.pow(base, index);
}, 0);
};