|
| 1 | +const resultEl = document.getElementById('result') |
| 2 | +const lengthEl = document.getElementById('length') |
| 3 | +const uppercaseEl = document.getElementById('uppercase') |
| 4 | +const lowercaseEl = document.getElementById('lowercase') |
| 5 | +const numbersEl = document.getElementById('numbers') |
| 6 | +const symbolsEl = document.getElementById('symbols') |
| 7 | +const textEl = document.getElementById('text') |
| 8 | +const generateEl = document.getElementById('generate') |
| 9 | +const clipboardBtn = document.getElementById('clipboard') |
| 10 | + |
| 11 | +const randomFunc = { |
| 12 | + lower: getRandomLower, |
| 13 | + upper: getRandomUpper, |
| 14 | + number: getRandomNumber, |
| 15 | + symbol: getRandomSymbol |
| 16 | +} |
| 17 | + |
| 18 | +clipboardBtn.addEventListener('click', () => { |
| 19 | + const password = resultEl.innerText |
| 20 | + if (!password) return |
| 21 | + navigator.clipboard.writeText(password) |
| 22 | +}) |
| 23 | + |
| 24 | +generateEl.addEventListener('click', () => { |
| 25 | + const hasLower = lowercaseEl.checked |
| 26 | + const hasUpper = uppercaseEl.checked |
| 27 | + const hasNumber = numbersEl.checked |
| 28 | + const hasSymbol = symbolsEl.checked |
| 29 | + const length = +lengthEl.value |
| 30 | + const text = textEl.value |
| 31 | + |
| 32 | + resultEl.innerText = generatePassword(hasLower, hasUpper, hasNumber, hasSymbol, text, length) |
| 33 | +}) |
| 34 | + |
| 35 | +function generatePassword(lower, upper, number, symbol, text, length) { |
| 36 | + let generatedPassword = text |
| 37 | + const typesCount = lower + upper + number + symbol |
| 38 | + const typesArr = [{ lower }, { upper }, { number }, { symbol }].filter(item => Object.values(item)[0]) |
| 39 | + |
| 40 | + if (typesCount === 0) { |
| 41 | + return text.slice(0, length) |
| 42 | + } |
| 43 | + |
| 44 | + |
| 45 | + while (generatedPassword.length < length) { |
| 46 | + typesArr.forEach(type => { |
| 47 | + const funcName = Object.keys(type)[0] |
| 48 | + generatedPassword += randomFunc[funcName]() |
| 49 | + }) |
| 50 | + } |
| 51 | + |
| 52 | + |
| 53 | + const finalPassword = generatedPassword.slice(0, length) |
| 54 | + |
| 55 | + return finalPassword |
| 56 | +} |
| 57 | + |
| 58 | +function getRandomLower() { |
| 59 | + return String.fromCharCode(Math.floor(Math.random() * 26) + 97) |
| 60 | +} |
| 61 | + |
| 62 | +function getRandomUpper() { |
| 63 | + return String.fromCharCode(Math.floor(Math.random() * 26) + 65) |
| 64 | +} |
| 65 | + |
| 66 | +function getRandomNumber() { |
| 67 | + return String.fromCharCode(Math.floor(Math.random() * 10) + 48) |
| 68 | +} |
| 69 | + |
| 70 | +function getRandomSymbol() { |
| 71 | + const symbols = '!@#$%^&*(){}[]=<>/,.' |
| 72 | + return symbols[Math.floor(Math.random() * symbols.length)] |
| 73 | +} |
0 commit comments