-
Notifications
You must be signed in to change notification settings - Fork 0
/
generator.js
80 lines (73 loc) · 2.53 KB
/
generator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// Getting the DOM Eleements
const resultDOM = document.getElementById('result');
const copybtnDOM = document.getElementById('copy');
const lengthDOM = document.getElementById('length');
const uppercaseDOM = document.getElementById('uppercase');
const numbersDOM = document.getElementById('numbers');
const symbolsDOM = document.getElementById('symbols');
const generatebtn = document.getElementById('generate');
const form = document.getElementById('passwordGeneratorForm');
// Generating Character Codes
const UPPERCASE_CODES = arrayFromLowToHigh(65, 90);
const LOWERCASE_CODES = arrayFromLowToHigh(97, 122);
const NUMBER_CODES = arrayFromLowToHigh(48, 57);
const SYMBOL_CODES = arrayFromLowToHigh(33, 47)
.concat(arrayFromLowToHigh(58, 64))
.concat(arrayFromLowToHigh(91, 96))
.concat(arrayFromLowToHigh(123, 126));
// Copy Password
copybtnDOM.addEventListener('click', () => {
const textarea = document.createElement('textarea');
const passwordToCopy = resultDOM.innerText;
// Edge Case when Password is Empty
if (!passwordToCopy) return;
// Copy Functionality
textarea.value = passwordToCopy;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
textarea.remove();
alert('Password Copied to Clipboard');
});
// Checking the options that are selected and setting the password
form.addEventListener('submit', (e) => {
e.preventDefault();
const characterAmount = lengthDOM.value;
const includeUppercase = uppercaseDOM.checked;
const includeNumbers = numbersDOM.checked;
const includeSymbols = symbolsDOM.checked;
const password = generatePassword(
characterAmount,
includeUppercase,
includeNumbers,
includeSymbols
);
resultDOM.innerText = password;
});
// Password Generating Function
let generatePassword = (
characterAmount,
includeUppercase,
includeNumbers,
includeSymbols
) => {
let charCodes = LOWERCASE_CODES;
if (includeUppercase) charCodes = charCodes.concat(UPPERCASE_CODES);
if (includeSymbols) charCodes = charCodes.concat(SYMBOL_CODES);
if (includeNumbers) charCodes = charCodes.concat(NUMBER_CODES);
const passwordCharacters = [];
for (let i = 0; i < characterAmount; i++) {
const characterCode =
charCodes[Math.floor(Math.random() * charCodes.length)];
passwordCharacters.push(String.fromCharCode(characterCode));
}
return passwordCharacters.join('');
};
// Character Code Generating Function
function arrayFromLowToHigh(low, high) {
const array = [];
for (let i = low; i <= high; i++) {
array.push(i);
}
return array;
}