-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfiscalCode.js
93 lines (72 loc) · 2.27 KB
/
fiscalCode.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
81
82
83
84
85
86
87
88
89
90
91
92
93
const fiscalCode = (person) => {
// Inital setup
let { name: firstName, surname: lastName, gender, dob } = person;
const months = { 1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "H", 7: "L", 8: "M", 9: "P", 10: "R", 11: "S", 12: "T" };
dob = person.dob.split("/").map((n) => +n);
// Build parts
function getLetters(string, letterType = "consonants") {
let vowels = string.match(/[aeiou]/gi);
let consonants = string.match(/[^aeiou]/gi);
if (letterType !== "consonants") {
return vowels;
}
return consonants;
}
function getLastNamePart(num) {
let part;
let lettersArr = getLetters(lastName);
if (lastName.length < 3) {
part = [...lastName].concat(["x"]);
} else if (num >= 3) {
part = lettersArr.slice(0, 3);
} else if (num < 3) {
part = lettersArr.slice(0, 2).concat(getLetters(lastName, "vowels").slice(0, 1));
} else {
part = null;
}
return part;
}
function getFirstnamePart(num) {
let part;
let lettersArr = getLetters(firstName);
if (firstName.length < 3) {
part = [...firstName].reverse().concat(["x"]);
} else if (num > 3) {
part = [lettersArr[0] + lettersArr[2] + lettersArr[3]];
} else if (num === 3) {
part = lettersArr;
} else if (num < 3) {
part = lettersArr.slice(0, 2).concat(getLetters(firstName, "vowels").slice(0, 1));
} else {
part = null;
}
return part;
}
function getGenderAndDobPart(letter, date) {
let part;
let [day, month, year] = date;
year = String(year).slice(2);
month = months[month];
if (letter === "F") {
day += 40;
} else if (letter === "M" && day < 10) {
day = 0 + String(day);
} else {
day = day;
}
part = [year, month, day];
return part;
}
// Build the final result
let consonantsInFirstName = getLetters(firstName).length;
let consonantsInLastName = getLetters(lastName).length;
let lastNamePart = getLastNamePart(consonantsInLastName);
let firstNamePart = getFirstnamePart(consonantsInFirstName);
let genderAndDobPart = getGenderAndDobPart(gender, dob);
let parts = [lastNamePart, firstNamePart, genderAndDobPart];
let final = parts
.map((part) => part.join(""))
.join("")
.toUpperCase();
return final;
};