Convert integer into its character equivalent, where 0 => a, 1 => b, etc
A simple answer would be (26 characters):
String.fromCharCode(97+n);
If space is precious you could do the following (20 characters):
(10+n).toString(36);
Think about what you could do with all those extra bytes!
How this works is you convert the number to base 36, so you have the following characters:
0123456789abcdefghijklmnopqrstuvwxyz
^ ^
n n+10
By offsetting by 10 the characters start at a
instead of 0
.
Not entirely sure about how fast running the two different examples client-side would compare though.
Will be more portable in case of extending to other alphabets:
char='abcdefghijklmnopqrstuvwxyz'[code]
or, to be more compatible (with our beloved IE):
char='abcdefghijklmnopqrstuvwxyz'.charAt(code);
Assuming you want lower case letters:
var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ...
97 is the ASCII code for lower case 'a'. If you want uppercase letters, replace 97 with 65 (uppercase 'A'). Note that if n > 25
, you will get out of the range of letters.
If you don't mind getting multi-character strings back, you can support arbitrary positive indices:
function idOf(i) {
return (
(i >= 26 ? idOf(((i / 26) >> 0) - 1) : "") +
"abcdefghijklmnopqrstuvwxyz"[i % 26 >> 0]
);
}
[0, 1, 25, 26, 27, 701, 702, 703].map(idOf);
// ['a', 'b', 'z', 'aa', 'ab', 'zz', 'aaa', 'aab']
(Not thoroughly tested for precision errors :)