Created
April 12, 2012 18:42
-
-
Save jqr/2369972 to your computer and use it in GitHub Desktop.
Encode/decode numbers as tiny strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TinyId | |
# All characters that URL encode to 1 character in size, minus the | |
# period which requires special Rails routing: | |
# (0..255).map(&:chr).select { |c| ERB::Util::u(c).size == 1 } - ['.'] | |
RAILS_URL = %w(- 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z _ a b c d e f g h i j k l m n o p q r s t u v w x y z) | |
# All BSON encodable string characters | |
BSON_STRING = (1..127).map(&:chr) | |
def initialize(alphabet) | |
@alphabet = alphabet | |
@size = @alphabet.size | |
end | |
# Encodes an integer as a TinyId. | |
def encode(integer) | |
remainder = integer.to_i | |
output = '' | |
loop do | |
output = @alphabet[remainder % @size] + output | |
remainder = remainder / @size | |
break if remainder == 0 | |
end | |
output | |
end | |
# Decodes a TinyId encoded string. | |
def decode(string) | |
value = 0 | |
string.reverse.split(//).each_with_index do |c, i| | |
value += @alphabet.index(c) * @size ** i | |
end | |
value | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment