File: base62.rb

package info (click to toggle)
ruby-base62 1.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, buster, forky, sid, trixie
  • size: 120 kB
  • sloc: ruby: 93; makefile: 3
file content (30 lines) | stat: -rw-r--r-- 641 bytes parent folder | download | duplicates (2)
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
require "base62/version"
require "base62/string"
require "base62/integer"

module Base62
  PRIMITIVES = (0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a
  
  class << self
    def decode(str)
      out = 0
      str.split(//).reverse.each_with_index do |char, index|
        place = PRIMITIVES.size ** index
        out += PRIMITIVES.index(char) * place
      end
      out
    end

    def encode(int)
      return "0" if int == 0

      rem = int
      result = ''
      while rem != 0
        result = PRIMITIVES[rem % PRIMITIVES.size].to_s + result
        rem /= PRIMITIVES.size
      end
      result
    end
  end
end