Module: Base62

Defined in:
lib/base62-rb.rb,
lib/base62/version.rb

Constant Summary collapse

KEYS =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
BASE =
KEYS.length
VERSION =
"0.1.1"

Class Method Summary collapse

Class Method Details

.decode(str) ⇒ Object

Eecodes base62 string to a base10 (decimal) number.



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/base62-rb.rb', line 22

def self.decode(str)
	num = 0
	i = 0
	# while loop is faster than each_char or other 'idiomatic' way
	while i < str.length
		pow = BASE ** (str.length - i -1)
		num += KEYS.index(str[i]) * pow
		i += 1
	end
	return num
end

.encode(num) ⇒ Object

Encodes base10 (decimal) number to base62 string.



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/base62-rb.rb', line 8

def self.encode(num)
	return "0" if num == 0
	return nil if num < 0

	str = ""
	while num > 0
		# prepend base62 charaters
		str = KEYS[num % BASE] + str
		num = num / (BASE)
	end
	return str
end