Module: Base62

Defined in:
lib/base62.rb

Overview

Modified version of: github.com/steventen/base62-rb

Class Method Summary collapse

Class Method Details

.decode(str) ⇒ Object

Decodes base62 string to a base10 (decimal) number.



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/base62.rb', line 25

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

.encode(num) ⇒ Object

Encodes base10 (decimal) number to base62 string.



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/base62.rb', line 11

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

  str = ""
  while num > 0
    # prepend base62 characters
    str = KEYS[num % BASE] + str
    num = num / BASE
  end
  str
end