forked from github/hubot-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base58.coffee
54 lines (48 loc) · 1.44 KB
/
base58.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# Description:
# Base58 encoding and decoding
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# hubot base58 encode|decode <query> - Base58 encode or decode <query>
#
# Author:
# jimeh
module.exports = (robot) ->
robot.respond /base58 encode( me)? (.*)/i, (msg) ->
try
msg.send Base58.encode(msg.match[2])
catch e
throw e unless e.message == 'Value passed is not an integer.'
msg.send "Base58 encoding only works with Integer values."
robot.respond /base58 decode( me)? (.*)/i, (msg) ->
try
msg.send Base58.decode(msg.match[2])
catch e
throw e unless e.message == 'Value passed is not a valid Base58 string.'
msg.send "Not a valid base58 encoded string."
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
Base58 = new Base58Builder()