Class: Exid::Base62

Inherits:
Object
  • Object
show all
Defined in:
lib/exid/base62.rb

Defined Under Namespace

Classes: DecodeError

Constant Summary collapse

CHARS =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
BASE =
CHARS.length
CHARS_HASH =
CHARS.each_char.zip(0...BASE).to_h
MAX_LENGTH =
22

Class Method Summary collapse

Class Method Details

.decode(str) ⇒ Object



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

def self.decode(str)
  max = str.length - 1
  str.each_char.zip(0..max).reduce(0) do |acc, (char, index)|
    character = CHARS_HASH[char]

    if character.nil?
      raise DecodeError, "Invalid character '#{char}' in string '#{str}'"
    end

    acc + (character * (BASE**(max - index)))
  end
end

.encode(num) ⇒ Object



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

def self.encode(num)
  result =
    (1..).reduce("") do |acc, _|
      break acc unless num.positive?

      num, remainder = num.divmod(BASE)
      CHARS[remainder] + acc
    end

  result.rjust(MAX_LENGTH, "0")
end