Are you looking to generate OTP codes for your application for authentication?
Follow these few steps and you will be able to do that.
STEP 1
Generate a random number between 0 and 9000
const randomNum = Math.random() * 9000
console.log(randomNum)
// will log random numbers like (1758.36816277815,8591.126356595876,380.85504639047053)
STEP 2
Format the random number, to eliminate the decimals
const randomNum = Math.random() * 9000
const formattedRandomNum = Math.floor(randomNum)
console.log(formattedRandomNum)
// will log random numbers like (1758,8591,380)
STEP 3
Add 1000 to the generated value to make sure the length is always 4.
Note: Math.random() will generate random numbers between 0 and 8999, so adding 1000 to this random number, the highest can only be 9999, so our max length of 4 is always ensured and preserved.
const randomNum = Math.random() * 9000
const token = Math.floor(1000 + randomNum)
console.log(token)
// will log random numbers like (2758,9591,1380)
STEP 4
Refactor into a function you can call each time you need to generate a token.
function generateToken(){
const randomNum = Math.random() * 9000
return Math.floor(1000 + randomNum)
}
// will log random numbers like (2758,9591,1380)
STEP 5
Call the function and your token is generated, then you can go ahead and hash the code/use it for what you intent.
function generateToken(){
const randomNum = Math.random() * 9000
return Math.floor(1000 + randomNum)
}
generateToken()
// will return random numbers like (2758,9591,1380)
Hope you found this content helpful?
Subscribe to my youtube channel here
Subscribe to my youtube channel
Top comments (5)
Why not just pad with zeros to preserve length? Then there are more potential codes...
That works too.
not correct, Token will be generate in string form.
const otpGenerator = () => Math.floor(Math.random()*9000)+1000
console.log(otpGenerator())
This will have all codes from
0000
to0999
missing.We're generating a 4 digit OTP to be used effectively as a temporary password. Digits are from 0-9. If we choose to generate a string, it doesn't matter since we'll be using it in a string-like context anyway. Using a string allows for 1000 more possible codes than just using an integer.
it's worked, but can you describe your code to understand for beginners.