Reputation: 79
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?
Upvotes: 2
Views: 199
Reputation: 39472
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.
Upvotes: 0