Friday, November 20, 2009

Counting in Base 36 with JavaScript and Ruby

Converting from Base 36 to integer in Ruby couldn't make this any easier:

str.to_i(36)

and back to Base 36:
int.to_s(36)

Humorously, JavaScript is very similar, just not as elegant:
parseInt(str, 36)

and back to Base 36:
int.toString(36)

Counting in Base 36 in both languages is an exercise in converting to integer incrementing and then converting back to Base 36:
def inc36(str)
n = str.to_i(36)
n += 1
n.to_s(36)
end

And in JavaScript:
function inc36(str) {
var n = parseInt(str, 36);
n++;
return n.toString(36);
}

Good times! I hope this helps someone. Googling for the answer did not turn up many hits.