2

I'm trying to find the way to encode some of data the need to send back to the API.

I've tried Base-x library but it didn't work.

Is there any other way to do this without programmatically without any library?

Max Kasem
  • 79
  • 9

1 Answers1

0

Here's how courtesy Bret Lowrey

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)
};

console.log(base62.encode(883314)); // Output - '3HN0'

console.log(base62.decode('3HN0')); // Output - 883314

Here's a Working Sample StackBlitz of the same thing as an Angular Service.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110