O ponto chave nesse desafio é a manipulação de strings e datas. Além disso, entender como funcionam as classes e como tirar proveito delas pode tornar o código mais organizado.
Em primeiro lugar, podemos definir os atributos da nossa classe que já conhecemos.
class Pilot { constructor(firstName, lastName, birthday) {
this.firstName = firstName
this.lastName = lastName
this.birthday = new Date(birthday)
this.flyingLicense = false
}
}
Para gerar a licença de voo vamos precisar do mês no formato MM, mas o método getMonth() do javascript retorna o mês como um número de 0 a 11, então vamos criar um método para lidar com isso:
class Pilot {
constructor(firstName, lastName, birthday) {
this.firstName = firstName
this.lastName = lastName
this.birthday = new Date(birthday)
this.flyingLicense = false
}
getBirthdayFullMonth() {
if (this.birthday.getMonth() < 9) {
return `0${this.birthday.getMonth() + 1}`
} else {
return `${this.birthday.getMonth() + 1}`
}
}
}
Por fim, vamos adicionar o método de gerar a licença. Para fazer isso basta seguir as regras definidas no enunciado:
class Pilot {
constructor(firstName, lastName, birthday) {
this.firstName = firstName
this.lastName = lastName
this.birthday = new Date(birthday)
this.flyingLicense = false
}
generateFlyingLicense() {
let license = ''
for (let i = 0; i < 5; i++) {
license += this.lastName[i] ? this.lastName[i].toUpperCase() : '9'
}
license += '-'
license += this.birthday.getFullYear().toString()[2]
license += this.getBirthdayFullMonth()
license += this.birthday.getFullYear().toString()[3]
license += '.'
license += this.firstName[0].toLowerCase()
this.flyingLicense = license
}
getBirthdayFullMonth() {
if (this.birthday.getMonth() < 9) {
return `0${this.birthday.getMonth() + 1}`
} else {
return `${this.birthday.getMonth() + 1}`
}
}
}