I love code snippet challenges
I stumbled upon a blog with a random code snippet challenge. Here was the problem at hand:
Given a String (x) containing only characters a-z, write a function (f) that returns a base 10 integer, which converts the String as if it were a base 26 numeral. Function f is bijective.
I wanted to give it a stab in javascript not because it sounded particularly difficult but to play with different javascript code styles. Here’s my 4 versions:
-
function f(i) {
-
-
if (!i) { return 0; }
-
-
var parts, n, pow, val;
-
parts = i.split(”);
-
parts.reverse();
-
-
val = 0;
-
pow = 1;
-
for (n = 0; n < parts.length; ++n) {
-
val += pow * (parts[n].charCodeAt(0) - 96);
-
pow = pow * 26;
-
}
-
-
return val;
-
}
The first one turns the string into an array and reverses it before doing the math loop. My next try eliminates the array and iterates backwards over the string.
-
function f(i) {
-
-
if (!i) { return 0; }
-
-
var n, mult = 1, val = 0, offset = 96, base = 26;
-
-
for (n = i.length - 1; n > -1; n–) {
-
val += mult * (i.charCodeAt(n) - offset);
-
mult = mult * base;
-
}
-
-
return val;
-
-
}
Here I’m playing with chaining array functions. While I don’t create an array, this is very similar to the first try.
-
function f(i) {
-
-
if (!i) { return 0; }
-
-
var mult = 1, val = 0, offset = 96, base = 26;
-
-
i.split(”).reverse().forEach(function(el) {
-
val += mult * (el.charCodeAt(0) - offset);
-
mult = mult * base;
-
});
-
-
return val;
-
-
}
Finally, recursion instead of an iterative loop.
-
function f(i, mult) {
-
-
if (!i) { return 0; }
-
if (!mult) { mult = 1; }
-
-
var offset = 96, base = 26;
-
return mult * (i.charCodeAt(i.length - 1) - offset)
-
+ f(i.substr(0, i.length - 1), mult * base);
-
-
}
Checkout the test output of my functions. Works in Firefox 1.5+ or other browsers that implement more modern javascript functions. Shouldn’t work in IE.
Mike :: Mar.17.2008 :: General :: No Comments »
