Skip to content

Instantly share code, notes, and snippets.

@igrigorik
Forked from veganstraightedge/gist:421959
Created July 25, 2010 15:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igrigorik/489622 to your computer and use it in GitHub Desktop.
Save igrigorik/489622 to your computer and use it in GitHub Desktop.
require "date"
require "time"
# converts base10 integers into NewBase60
def num_to_sxg(num=nil)
sxg = ""
vocabulary = "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ_abcdefghijkmnopqrstuvwxyz"
return 0 if num.nil? || num.zero?
while num > 0 do
mod = num % 60
sxg = "#{vocabulary[mod,1]}#{sxg}"
num = (num - mod) / 60
end
sxg
end
# converts base10 integers into NewBase60 padding with leading zeroes
def num_to_sxgf(num, padding)
str = num_to_sxg(num)
padding = 1 if padding.nil?
padding -= str.length
while padding > 0
str = "0#{str}"
padding -= 1
end
str
end
# converts NewBase60 into base10 integer
def sxg_to_num(str)
num = 0
str.length.times do |index| # iterate over each letter
char = str[index] # grab the ascii value of the current letter
if (48..57).include?(char)
char -= 48
elsif (65..72).include?(char)
char -= 55
elsif (char == 73 || char == 108) # typo capital I, lowercase l to 1
char = 1
elsif (74..78).include?(char)
char -= 56
elsif (char == 79) # error correct typo capital O to 0
char = 0
elsif (80..90).include?(char)
char -= 57
elsif (char==95) # underscore
char = 34
elsif (97..107).include?(char)
char -= 62
elsif (109..122).include?(char)
char -= 63
else
char = 0 # treat all other noise as 0
end
num = 60 * num + char
end
num
end
# converts NewBase60 characters into a Time object
def sxg_to_time(str)
# days since epoch * seconds * minutes * hours + timezone
Time.at(sxg_to_num(str) * 60 * 60 * 24 + Time.now.gmtoff.abs)
end
# converts Time object into a NewBase60 characters
def time_to_sxg(time)
the_when = time + Time.now.gmtoff.abs
epoch_days = the_when.to_i / 60 / 60 / 24
num_to_sxg(epoch_days)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment