Encoding/decoding base 62 in ES6 JavaScript

It's easy to encode numbers to string in JavaScript. It had native base 64 encoding and decoding (atob and btoa respectively) for a long time.

One kind of encoding that has become increasingly popular on the web is base 62. While not as efficient, due to the loss of two characters, it is useful when you need to encode a number in a URL. You see this all the time in things like URL shorteners or Youtube IDs.

const base62 = {  
  charset: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    .split(''),
  encode: integer => {
    if (integer === 0) {
      return 0;
    }
    let s = [];
    while (integer > 0) {
      s = [base62.charset[integer % 62], ...s];
      integer = Math.floor(integer / 62);
    }
    return s.join('');
  },
  decode: chars => chars.split('').reverse().reduce((prev, curr, i) =>
    prev + (base62.charset.indexOf(curr) * (62 ** i)), 0)
};

See this code with some test cases in the JSFiddle

Bret Lowrey

Code is like a war - the best code is one never written.

Florida, USA