1+ const characterAmountRange = document . getElementById ( 'characterAmountRange' )
2+ const characterAmountNumber = document . getElementById ( 'characterAmountNumber' )
3+ const includeUppercaseElement = document . getElementById ( 'includeUppercase' )
4+ const includeNumbersElement = document . getElementById ( 'includeNumbers' )
5+ const includeSymbolsElement = document . getElementById ( 'includeSymbols' )
6+ const form = document . getElementById ( 'passwordGeneratorForm' )
7+ const passwordDisplay = document . getElementById ( 'passwordDisplay' )
8+
9+ const UPPERCASE_CHAR_CODES = arrayFromLowToHigh ( 65 , 90 )
10+ const LOWERCASE_CHAR_CODES = arrayFromLowToHigh ( 97 , 122 )
11+ const NUMBER_CHAR_CODES = arrayFromLowToHigh ( 48 , 57 )
12+ const SYMBOL_CHAR_CODES = arrayFromLowToHigh ( 33 , 47 ) . concat (
13+ arrayFromLowToHigh ( 58 , 64 )
14+ ) . concat (
15+ arrayFromLowToHigh ( 91 , 96 )
16+ ) . concat (
17+ arrayFromLowToHigh ( 123 , 126 )
18+ )
19+
20+ characterAmountNumber . addEventListener ( 'input' , syncCharacterAmount )
21+ characterAmountRange . addEventListener ( 'input' , syncCharacterAmount )
22+
23+ form . addEventListener ( 'submit' , e => {
24+ e . preventDefault ( )
25+ const characterAmount = characterAmountNumber . value
26+ const includeUppercase = includeUppercaseElement . checked
27+ const includeNumbers = includeNumbersElement . checked
28+ const includeSymbols = includeSymbolsElement . checked
29+ const password = generatePassword ( characterAmount , includeUppercase , includeNumbers , includeSymbols )
30+ passwordDisplay . innerText = password
31+ } )
32+
33+ function generatePassword ( characterAmount , includeUppercase , includeNumbers , includeSymbols ) {
34+ let charCodes = LOWERCASE_CHAR_CODES
35+ if ( includeUppercase ) charCodes = charCodes . concat ( UPPERCASE_CHAR_CODES )
36+ if ( includeSymbols ) charCodes = charCodes . concat ( SYMBOL_CHAR_CODES )
37+ if ( includeNumbers ) charCodes = charCodes . concat ( NUMBER_CHAR_CODES )
38+
39+ const passwordCharacters = [ ]
40+ for ( let i = 0 ; i < characterAmount ; i ++ ) {
41+ const characterCode = charCodes [ Math . floor ( Math . random ( ) * charCodes . length ) ]
42+ passwordCharacters . push ( String . fromCharCode ( characterCode ) )
43+ }
44+ return passwordCharacters . join ( '' )
45+ }
46+
47+ function arrayFromLowToHigh ( low , high ) {
48+ const array = [ ]
49+ for ( let i = low ; i <= high ; i ++ ) {
50+ array . push ( i )
51+ }
52+ return array
53+ }
54+
55+ function syncCharacterAmount ( e ) {
56+ const value = e . target . value
57+ characterAmountNumber . value = value
58+ characterAmountRange . value = value
59+ }
0 commit comments