I need to create unique referral codes. To make each Referral code unique I am trying to do something like below.
const stringVal = `${currentTimestamp}$
FWIW, the following are two helper functions that convert a BigInt to a desired base and vice versa...
var digits = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
function bigint2base( x, baseDigits ) {
let base = BigInt( baseDigits.length );
let result = '';
while ( 0 < x ) {
result = baseDigits.charAt( Number( x % base ) ) + result;
x = x / base;
}
return result || '0';
}
function base2bigint( x, baseDigits ) {
let base = BigInt( baseDigits.length );
let result = 0n;
for ( let i = 0; i < x.length; i++ ) {
result = result * base + BigInt( baseDigits.indexOf( x.charAt( i ) ) );
}
return result;
}
console.log( `BigInt 158632196111710003n to base62 ( '${digits}' )...`);
base62val = bigint2base( 158632196111710003n, digits );
console.log( base62val );
console.log( `Converted back to BigInt is...` );
console.log( base2bigint( base62val, digits ).toString() );
console.log('');
console.log( `BigInt 31957108571341948394931814703184314387417471347093174n to base62 ( '${digits}' )...`);
base62val = bigint2base( 31957108571341948394931814703184314387417471347093174n, digits );
console.log( base62val );
console.log( `Converted back to BigInt is...` );
console.log( base2bigint( base62val, digits ).toString() );
Hope this helps...