base62-rb 0.1.1 → 0.2.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/lib/base62-rb.rb +6 -4
- data/lib/base62/version.rb +1 -1
- metadata +1 -1
checksums.yaml
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
---
|
2
2
|
SHA1:
|
3
|
-
metadata.gz:
|
4
|
-
data.tar.gz:
|
3
|
+
metadata.gz: 729b23f1bf5f70dc6aa94e03c7188d83dd197b57
|
4
|
+
data.tar.gz: a9d5c5b971eed05ce46ab22fa24bcd162ed993b2
|
5
5
|
SHA512:
|
6
|
-
metadata.gz:
|
7
|
-
data.tar.gz:
|
6
|
+
metadata.gz: f40f4e4f512c0ef983583350c87d468bb5bd325df6dc88ac447ca862bd94e52ec4b24ea520af0f641894c79136a65c30a0c1a30fd40ac96f86c8759aa8e55494
|
7
|
+
data.tar.gz: 8fed19731093b78e6c9ab87b9f967ec00ee0abfb2cbd1b8ab0e8d3dcd035daff7c4c79f0910935cd26350764764709f09c06dc9fceb95d229655ef670dac2039
|
data/lib/base62-rb.rb
CHANGED
@@ -2,6 +2,7 @@ require "base62/version"
|
|
2
2
|
|
3
3
|
module Base62
|
4
4
|
KEYS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
5
|
+
KEYS_HASH = KEYS.each_char.with_index.inject({}){ |h,(k,v)| h[k]=v; h }
|
5
6
|
BASE = KEYS.length
|
6
7
|
|
7
8
|
# Encodes base10 (decimal) number to base62 string.
|
@@ -13,19 +14,20 @@ module Base62
|
|
13
14
|
while num > 0
|
14
15
|
# prepend base62 charaters
|
15
16
|
str = KEYS[num % BASE] + str
|
16
|
-
num
|
17
|
+
num /= BASE
|
17
18
|
end
|
18
19
|
return str
|
19
20
|
end
|
20
21
|
|
21
|
-
#
|
22
|
+
# Decodes base62 string to a base10 (decimal) number.
|
22
23
|
def self.decode(str)
|
23
24
|
num = 0
|
24
25
|
i = 0
|
26
|
+
len = str.length - 1
|
25
27
|
# while loop is faster than each_char or other 'idiomatic' way
|
26
28
|
while i < str.length
|
27
|
-
pow = BASE ** (
|
28
|
-
num +=
|
29
|
+
pow = BASE ** (len - i)
|
30
|
+
num += KEYS_HASH[str[i]] * pow
|
29
31
|
i += 1
|
30
32
|
end
|
31
33
|
return num
|
data/lib/base62/version.rb
CHANGED