0

Possible Duplicate:
Convert a number to the shortest possible character string while retaining uniqueness

I want to count something and I only have a single digit to report the result, so I want to use letters for numbers > 9. E.g.

1 => 1
5 => 5
10 => A
30 => U
55 => u   // I may have an off-by-one error here -- you get the idea
>61 => z  // 60 will be more than enough, so I'll use z to mean "at least 62"

What's the easiest way to do that using javascript?

Community
  • 1
  • 1
sprugman
  • 19,351
  • 35
  • 110
  • 163

3 Answers3

0

Here's one of the many ways to do it:

function num2letter(num) {
    if( num > 61) return "z";
    if( num < 0) return num;
    return "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[num];
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

I decided base 36 was good enough:

function oneDigit(n) {
    var BASE=36;
    if (n >= BASE-1) { n = BASE-1; }
    return n.toString(BASE);
}
sprugman
  • 19,351
  • 35
  • 110
  • 163
0

Another way to do it:

function parse(x)
{
    if(x<10)return x;
    else if(x<36)return String.fromCharCode(x+55).toUpperCase();
    else if(x<62)return String.fromCharCode(x+29).toLowerCase();
    else return "z";
}

And this little test:

var res="";
for(var a=-10;a<70;a++)res+=a+" -> "+parse(a)+"\n";
alert(res);

And a fiddle: http://jsfiddle.net/nD59z/4/

And the same way, but with less characters and incomprehensible:

function parse(x)
{
    return x<10?x:(x<36?String.fromCharCode(x+55).toUpperCase():(x<62?String.fromCharCode(x+29).toLowerCase():"z"));
}
Alexandre Khoury
  • 3,896
  • 5
  • 37
  • 58