Skip to content

Instantly share code, notes, and snippets.

@h2xd
Last active July 27, 2020 09:57
Show Gist options
  • Save h2xd/81d4605ad1c876bb34e8c61316507430 to your computer and use it in GitHub Desktop.
Save h2xd/81d4605ad1c876bb34e8c61316507430 to your computer and use it in GitHub Desktop.
Generate a random password in JavaScript; based on your char selection
const getRandomCharsFromString = (charset, length) =>
charset.split('')
.sort(() => Math.random() - 0.5)
.slice(0, length)
.join('')
export const generateRandomPassword = () => (
[
getRandomCharsFromString('0123456789', 4),
getRandomCharsFromString('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 6),
getRandomCharsFromString('abcdefghijklmnopqrstuvwxyz', 6),
getRandomCharsFromString('.,<>;:?&*!@#$%', 4),
]
.join('')
.split('')
.sort(() => Math.random() - 0.5)
.join('')
)
const getRandomCharsFromString = (charset: string, length: number) =>
charset.split('')
.sort(() => Math.random() - 0.5)
.slice(0, length)
.join('')
export const generateRandomPassword = (): string => (
[
getRandomCharsFromString('0123456789', 4),
getRandomCharsFromString('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 6),
getRandomCharsFromString('abcdefghijklmnopqrstuvwxyz', 6),
getRandomCharsFromString('.,<>;:?&*!@#$%', 4),
]
.join('')
.split('')
.sort(() => Math.random() - 0.5)
.join('')
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment