-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
82 lines (68 loc) · 2.12 KB
/
main.js
File metadata and controls
82 lines (68 loc) · 2.12 KB
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
81
82
const resultElement = document.querySelector("#result");
const lengthElement = document.querySelector("#length");
const capitalElement = document.querySelector("#capital");
const smallElement = document.querySelector('#small');
const numberElement = document.querySelector('#number');
const specialElement = document.querySelector('#symbol');
const form = document.querySelector('#pg-form');
const clipBoard = document.querySelector('.clipboard');
const fieldsArray = [
{
field: capitalElement,
getChar: getCapitalLetter
},
{
field: smallElement,
getChar: getSmallLetter
},
{
field: numberElement,
getChar: getNumber
},
{
field: specialElement,
getChar: getSpecialChar
},
];
function getRandomChar(min, max) {
const limit = max - min +1; //4 -> 2 . ascii code
return String.fromCharCode(Math.floor(Math.random() * limit) + min);
}
function getCapitalLetter(){
return getRandomChar(65, 90);
}
function getSmallLetter(){
return getRandomChar(97, 122);
}
function getNumber(){
return getRandomChar(48, 57);
}
function getSpecialChar(){
return getRandomChar(33, 47);
}
function getSpecialChar(){
const specialChar = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~'";
return specialChar[Math.floor(Math.random() * specialChar.length)];
}
form.addEventListener('submit', (e) => {
e.preventDefault();
const length = lengthElement.value;
let generatedPassword = '';
const checkedFields = fieldsArray.filter(({field})=> field.checked);
for(i=0; i<length; i++){
const index = Math.floor(Math.random() * checkedFields.length);
const letter = checkedFields[index].getChar();
generatedPassword += letter;
}
resultElement.value = generatedPassword;
});
clipBoard.addEventListener('click', async(e) => {
const text = resultElement.value;
if(text){
await navigator.clipboard.writeText(text);
alert('Copied to your clipboard');
}
else{
alert('No password to copy');
}
});