Himmators Himmators - 4 months ago 16
Node.js Question

Convert number to characters?

I have a system where users must write userid:s into their phone. I want to obfuscate the id:s so that it is fairly hard to guess the number and then I want to convert it into a base-23 number using the following characters:


I'm droppin I,L and O, because those characters seriously suck in id-numbers.

So forexample if the input is
, the output would be
would be
etc. (I will scramble/unscramble the userIds before I run them through this function)

I'm trying to figure out how to convert the integer into a letter. this is the best I can com up with:

var scrambled = 234,
charmap = ['a','b','c'...]


Here I would like to do charmap[scrambled] for every single character and save it to a string, I could convert the scrambled to a string and split it, but I think there is a cleaner way of doing it. Modern web tech is ok!


Since your charmap is not trivial, you could instead write your own function. With the charmap hidden in a closure.

Here is a complete fiddle, provinding two side conversion object:

var convert = (function() {
  var base = 23;
  var charmap = "abcdefghjkmnpqrstuvwxyz";
  return {
    toString: function(i) {
      var result = "";
      do {
        result = charmap.charAt(i % base) + result;
        i = (i - i % base) / base;
      } while (i > 0);

      return result;
    fromString: function(s) {
      var result = 0;
      for (var i = 0; i < s.length; ++i) {
        var k = charmap.indexOf(s.charAt(i));
        result = result * base + k;

      return result;

for (var i = 0; i < 100; ++i) {
  if (convert.fromString(convert.toString(i)) !== i) {
    console.log("error at " + i);