Created
September 24, 2025 21:12
-
-
Save Gipetto/ecef81aec3dd5c0995a4208790378f7a to your computer and use it in GitHub Desktop.
Random password generation in js/ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const arrayShuffle = (input: string[]): string[] => { | |
| let i = input.length; | |
| const arr: string[] = [...input]; | |
| while (i != 0) { | |
| const ri = Math.floor(Math.random() * i); | |
| i--; | |
| [arr[i], arr[ri]] = [arr[ri], arr[i]]; | |
| } | |
| return arr; | |
| }; | |
| export const generatePassword = (length: number = 18) => { | |
| const chars = []; | |
| // printable ascii chars are 33 through 126 | |
| for (let i = 33; i <= 126; i++) { | |
| const char = String.fromCharCode(i); | |
| let fill: number; | |
| switch (true) { | |
| case i >= 97 && i <= 122: | |
| case i >= 48 && i <= 57: | |
| // numbers & lower case letters | |
| fill = 3; | |
| break; | |
| case i >= 65 && i <= 90: | |
| // upper case letters | |
| fill = 2; | |
| break; | |
| default: | |
| // special chars | |
| fill = 1; | |
| } | |
| chars.push(...new Array(fill).fill(char)); | |
| } | |
| const shuffled = arrayShuffle(chars); | |
| return shuffled.slice(0, length).join(""); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment