Computer >> Computer tutorials >  >> Programming >> Javascript

Convert number to characters in JavaScript


Suppose we have a login system where users are required to provide a unique userID to uniquely identify them. And for obvious security reasons, we want to obfuscate the userID so that it is fairly hard to guess the number.

Basically, we are required to write two functions.

  • encode(),

  • decode()

The first function should convert our number input into a base 26 alphabet mapping. And the second function should convert the alphabet mapping back into the original number.

Although this isn't very practical as most of the Hashing algorithms do not provide to and fro conversions, but for the purpose of this question, we are not considering that.

For example − If the number is 31, then,

encode(31) = 'ea'
and, decode('ea') = 31

Example

The code for this will be −

const num = 31;
const encode = num => {
   let res = '';
   const legend = 'zabcdefghijklmnopqrstuvwxy';
   while(num){
      const rem = num % (legend.length);
      res += legend[rem];
      num = (Math.floor(num / legend.length));
   };
   return res;
};
const decode = str => {
   let num = 0;
   const legend = 'zabcdefghijklmnopqrstuvwxy';
   for(let i = 0; i < str.length; i++){
      const ind = legend.indexOf(str[i]);
      num += (ind * Math.pow(legend.length, i));
   };
   return num;
}
console.log(encode(num));
console.log(decode('ea'));

Output

And the output in the console will be −

ea
31