-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerateCEP.js
More file actions
69 lines (57 loc) · 1.78 KB
/
generateCEP.js
File metadata and controls
69 lines (57 loc) · 1.78 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
class InvalidCEPLengthError extends Error {
constructor(message) {
super(message);
this.name = 'InvalidCEPLengthError';
}
}
class InvalidCEPCharacterError extends Error {
constructor(message) {
super(message);
this.name = 'InvalidCEPCharacterError';
}
}
class InvalidCEPError extends Error {
constructor(message) {
super(message);
this.name = 'InvalidCEPError';
}
}
function generateCEP() {
let cep = '';
for (let i = 0; i < 8; i++) {
cep += Math.floor(Math.random() * 10);
}
return cep;
}
function validateCEP(cep) {
cep = cep.replace(/[^\d]/g, ''); // Remove todos os caracteres não numéricos
if (cep.length !== 8) {
throw new InvalidCEPLengthError('CEP deve ter 8 dígitos');
}
// Aqui você pode adicionar outras validações, se necessário
return true;
}
function formatCEP(cep) {
cep = cep.replace(/[^\d]/g, ''); // Remove todos os caracteres não numéricos
if (cep.length !== 8) {
throw new InvalidCEPLengthError('Comprimento de CEP inválido');
}
return cep.replace(/(\d{5})(\d{3})/, '$1-$2');
}
try {
const cep = generateCEP();
const formattedCep = formatCEP(cep);
console.log("CEP: ", cep);
console.log("Formatted CEP: ", formattedCep);
console.log("Valid: ", validateCEP(cep));
} catch (error) {
if (error instanceof InvalidCEPLengthError) {
console.error('CEP Length Error: ', error.message);
} else if (error instanceof InvalidCEPCharacterError) {
console.error('CEP Character Error: ', error.message);
} else if (error instanceof InvalidCEPError) {
console.error('Invalid CEP Error: ', error.message);
} else {
console.error('An unknown error occurred: ', error.message);
}
}