Is there the way to encode base62 string in Angular 7?

182 Views Asked by At

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?

1

There are 1 best solutions below

1
SiddAjmera On

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.