Skip to content

Instantly share code, notes, and snippets.

@samsoft00
Created January 18, 2022 14:32
Show Gist options
  • Save samsoft00/c931524ff9cdb28d5fbe55326cc21273 to your computer and use it in GitHub Desktop.
Save samsoft00/c931524ff9cdb28d5fbe55326cc21273 to your computer and use it in GitHub Desktop.
Class to generate random number.
export class Generator {
// constructor (private readonly len: number = 6) {}
len: number = 10
randomNumber (): string {
return Math.floor(
Math.pow(10, this.len - 1) +
Math.random() * (Math.pow(10, this.len) - Math.pow(10, this.len - 1) - 1)
).toString()
}
randomString (): string {
let randomString = ''
const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
for (let i = 0; i < this.len; i += 1) {
const randomPoz = Math.floor(Math.random() * charSet.length)
randomString += charSet.substring(randomPoz, randomPoz + 1)
}
return randomString
}
getPrefix (length: number = NaN): string {
const charSet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
this.len = !isNaN(length) ? length : this.len
return Array.apply(null, Array(this.len))
.map(() => {
return charSet.charAt(Math.floor(Math.random() * charSet.length))
})
.join('')
}
/**
* Generate 6 digits token
*/
generateToken (): string {
const dateTime = new Date()
return (Math.floor(dateTime.getTime() * 90000) + 10000).toString().substring(8, 14)
}
generateOtp (): string {
return `${this.getPrefix(3)}${this.generateToken().substring(2, 6)}`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment