I need to create unique referral codes. To make each Referral code unique I am trying to do something like below.
const stringVal = `${currentTimestamp}${someVal}${someKey}`
Here someVal
itself is BigInt mysql datatype, and someKey
will always be two digit number.
To encode, I am using base62 package.
Whever I pass someVal
more than 99, I start to get unexpected results.
function generateReferralCode(someVal) {
const currentTimestamp = Date.now()
let someKey = getSomeKey(someVal)
const val = `${currentTimestamp}${someVal}${someKey}`
console.log(`number to string : ${val}`)
console.log(`longed value from string : ${Long.fromString(val)}`)
const encodedVal = await base62.encode(Long.fromString(val))
return encodedVal
}
function parseReferralCode(referralCode) {
const decodedVal = base62.decode(referralCode)
console.log(`decoded number : ${decodedVal}`)
//extract someValue
let somevalue = parseInt(decodedVal / 100) % ( Math.pow(10, (decodedVal % 100)))
return someValue
}
async function test() {
const encoded = await generateReferralCode(100)
console.log(`encoded val: ${encoded}`)
const decoded = await parseReferralCode(encoded)
console.log(`decoded val: ${decoded}`)
}
test()
Output:
number to string : '158632196111710003'
longed value from string : 158632196111710003
encoded val: 'bIxiLMdWrm'
decoded number : 158632196111710000 //this should be as encoded string or longed val
decoded val: 1586321961117100 //this should be 100
The above doesn't work for value of someValue > 99
. I know it's because of integer
length in javascript.
I also tried using long, but it is also not working.
I think base62
package also don't support big integers.
Can someone help how can I base62
encode that kind of big numbers?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…