1+ //DOM Elements
2+ const passwordElem = document . querySelector ( '.password' ) ;
3+ const btnElem = document . getElementById ( 'btn-generate' ) ;
4+ const passwordLengthElem = document . getElementById ( 'password-length-number' ) ;
5+ const lowercaseElem = document . getElementById ( 'lowercase' ) ;
6+ const uppercaseElem = document . getElementById ( 'uppercase' ) ;
7+ const numbersElem = document . getElementById ( 'numbers' ) ;
8+ const symbolsElem = document . getElementById ( 'symbols' ) ;
9+
10+ //when user clicks on btn, generate a new password
11+ btnElem . addEventListener ( 'click' , updateUI ) ;
12+
13+ //display generated password on UI
14+ function updateUI ( ) {
15+ const passwordLength = passwordLengthElem . value ;
16+ const includeLowercase = lowercaseElem . checked ;
17+ const includeUppercase = uppercaseElem . checked ;
18+ const includeNumbers = numbersElem . checked ;
19+ const includeSymbols = symbolsElem . checked ;
20+ const password = generatePassword ( passwordLength , includeLowercase , includeUppercase , includeNumbers , includeSymbols ) ;
21+ passwordElem . innerText = password ;
22+ }
23+
24+ function generatePassword ( len , isLC , isUC , isNum , isSym ) {
25+ let charCodes = [ ] ;
26+ if ( isLC )
27+ charCodes = LOWERCASE_CHAR_CODES ;
28+ if ( isUC )
29+ charCodes = charCodes . concat ( UPPERCASE_CHAR_CODES ) ;
30+ if ( isNum )
31+ charCodes = charCodes . concat ( NUMBER_CHAR_CODES ) ;
32+ if ( isSym )
33+ charCodes = charCodes . concat ( SYMBOL_CHAR_CODES ) ;
34+
35+ const finalPassword = [ ] ;
36+ for ( let i = 0 ; i < len ; i ++ ) {
37+ const randomCode = charCodes [ Math . floor ( Math . random ( ) * charCodes . length ) ] ;
38+ finalPassword . push ( String . fromCharCode ( randomCode ) ) ;
39+ }
40+
41+ //if all of the checkbox are unchecked
42+ if ( charCodes . length === 0 )
43+ return `Select at least one option` ;
44+
45+ return finalPassword . join ( '' ) ; //return string of array finalPassword
46+ }
47+
48+ function arrayLowToHigh ( low , high ) {
49+ let array = [ ] ;
50+ for ( let i = low ; i <= high ; i ++ ) {
51+ array . push ( i ) ;
52+ }
53+ return array ;
54+ }
55+
56+ //Arrays storing all our characters
57+ const LOWERCASE_CHAR_CODES = arrayLowToHigh ( 97 , 122 ) ;
58+ const UPPERCASE_CHAR_CODES = arrayLowToHigh ( 65 , 90 ) ;
59+ const NUMBER_CHAR_CODES = arrayLowToHigh ( 48 , 57 ) ;
60+ const SYMBOL_CHAR_CODES = arrayLowToHigh ( 33 , 47 )
61+ . concat ( arrayLowToHigh ( 58 , 64 ) )
62+ . concat ( arrayLowToHigh ( 91 , 96 ) )
63+ . concat ( arrayLowToHigh ( 123 , 126 ) ) ;
0 commit comments