Contenido del curso
Fundamentos de POO
POO Avanzada
Asincronismo y consumo de APIs
Genéricos
Próximos pasos
Métodos
Contenido del curso
Métodos
William Cortes
EstudianteLuis Ariza
EstudianteJosue Cerron Tuesta
EstudianteAxel Enrique Galeed Gutierrez
EstudianteEduardo Esteban Álvarez Castañeda
EstudianteAxel Enrique Galeed Gutierrez
EstudianteJordy Mairena Montoya
EstudianteRonaldo Delgado
EstudianteCHRISTIAN OLIVER SOLANO NUÑEZ
EstudianteKevin Daniel Guzman Delgadillo
EstudianteJesus Abel Jimenez Bracho
EstudianteJavier Alejandro Albornoz Pérez
EstudianteJohan Sebastian
EstudianteKellbis Salazar
EstudianteVictor Perozo
EstudianteAndrés Corral
EstudiantePaula Catalina Delgado Almendrales
EstudianteJose Gregorio Sarabia Lugo
EstudianteDavid Rangel
EstudiantePedro Carreño
EstudianteJose Ever Muñoz Muñoz
EstudianteValentina Hernández
EstudianteJuan David Marin Rodriguez
EstudianteDiego Raciel Ortega Hernandez
Estudianteoscar.rusinque
EstudianteWinslow Taylor Geldres Oliveros
EstudianteRonaldo Delgado
EstudianteEntendí que: métodos => Funciones dentro de una clase. propiedades ó atributos => Variables (ó constantes) dentro de una clase.
¡¡Entendiste bien!! 👍
Así es bro!
Les comparto mis apuntes. :D
¿Qué hacen los métodos?
Describen el comportamiento de los objetos.
Sintaxis
class nameClass { constructor (parameters) { statements } methodName (parameters: dataTypes): dataType { statements } }
Ojo que una buena práctica, es crear los nombres de las clases en formato PascalCase
Hola, @Proskynete, tenés toda la razón, se me escapó ese typo.
Mi solucion
export type formatDate = 'days' | 'months' | 'years'; class MyDate { year: number; month: number; day: number; leapYear: boolean = false; // by deafault the year is not leap year private _months: { [key: number]: string; } = { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December' }; private _month31: number[] = [1, 3, 5, 7, 8, 10, 12]; // list of months that have 31 days constructor(year: number, month: number, day: number) { this.year = this._validYear(year); this._leapYear() this.month = this._validMonth(month); this.day = this._validDay(day); } printFormat(format: string = 'dd / mm / yy'): string { if (this._validError() == null) { // if validError returns null then there are no errors format = format.replace('yy', this.year.toString()); format = format.replace('dd', this.day.toString()); format = format.replace('mm', this.month.toString()); format = format.replace('mn', this._months[this.month]); return format; } else { return this._validError()!; // notation ! tells typescript that the programmer is in control } } private _validError(): string | null { // if any attribute has the value of zero then it is out of range and there is an error let error: string = '#outRange!'; // out of tange error indicator if (this.year == 0) { return `${error} year`; // error message } if (this.month == 0) { return `${error} month`; // error message } if (this.day == 0) { return `${error} day`; // error message } return null; // whithout errors } private _validYear(year: number) { // if the year is greater than zero it is valid if(year > 0) { return year; } else { return 0; } } private _validDay(day: number) { // validate the day if (day > 0) { if (this.month === 2) { // if the month is february let evaluateDay: number = 28; if (this.leapYear) { // if leap year evaluateDay++; } if (day <= evaluateDay) { return day; } else { return 0; } } else { // if it is any month except february let evaluateDay: number = 30; if (this._month31.includes(this.month)) { // if the month has 31 days evaluateDay++; } if (day <= evaluateDay) { return day; } else { return 0; } } } else { return 0 } } private _validMonth(month: number) { // Validated that the month is between 1 and 12 if (month > 0 && month < 13) { return month; } else { return 0; } } private _leapYear() { /** * @ Check if the year is a leap year */ let result: number; result = (this.year / 4) % 2; // formula if ((n/4) % 2 == 0) if(result == 0) { this.leapYear = true; } } add(amount: number, format: formatDate) { if (this._validError() == null) { if (format == 'days') { for (let i = 0; i < amount; i++) { this.day += 1; if (this._validDay(this.day) == 0) { // Validated the day based on the month and year /* if _validDay returns 0 the valid days for the current month were exceeded then the month is increased and day is restarted */ this.month++; if (this.month == 13) { this.year++; this.month = 1; } this.day = 1; } } } else if (format == 'months') { for (let i = 0; i < amount; i++) { this.month++; if (this.month > 12) { this.year++; this.month = 1; } } } else if (format == 'years') { if (amount > 0) { this.year += amount; } } } } } const myDate = new MyDate(2000, 2, 29); console.log(myDate.printFormat('dd of mn of yy')); myDate.add(36, 'days'); console.log(myDate.printFormat()); myDate.add(40, 'months'); console.log(myDate.printFormat('mm - dd - yy'));
Genial!
mi solución para sumar fechas considerando años bisiestos :
add(amount:number, type: 'days' | 'months' | 'years') { if(type === 'days') { if(this.month === 4 || this.day === 6 || this.day === 9 || this.day === 11) { this.sumByDays(amount, 30); }else if(this.month === 2){ if(this.isLeapYear(this.year)){ this.sumByDays(amount, 29); } else { this.sumByDays(amount, 28); } }else { for(let x = 1; x <= amount; x++){ if(this.day < 31){ this.day++; }else { this.day = 0; this.day++; if(this.month === 12){ this.month = 1; this.year += 1; }else { this.month += 1; } } } } } if(type === 'months') { for(let x = 1; x <= amount; x++){ if(this.month < 12){ this.month++; }else { this.month = 0; this.month++; this.year += 1; } } } if(type === 'years') { this.year += amount; } }; sumByDays(sum: number, days: number){ for(let x = 1; x <= sum; x++){ if(this.day < days){ this.day++; }else { this.day = 0; this.day++; this.month += 1; } } }; isLeapYear(year: number){ //calculo año bisisesto return ((year % 4) === 0 && (year % 100) != 0 || ((year % 400) === 0)); };
¿Y si añado por ejemplo 100 días o 24 meses? ... si se lo preguntaron aquí está el código:
export class MyDate { year: number; month: number; day: number; constructor(year: number, month: number, day: number) { this.year = year; this.month = month; this.day = day; } printFormattedDate(): string { return `${this.year}/${this.month}/${this.day}`; } add(amount: number, type: 'd' | 'm' | 'y') { const funcOperators = { d: (amount: number) => { this.day += amount; if (this.day > 30) this.day = this.day % 365 % 30; return Math.floor(amount / 30); }, m: (amount: number) => { this.month += amount; if (this.month > 12) this.month = this.month % 12; return Math.floor(amount / 12); }, y: (amount: number) => { this.year += amount; return 0; }, }; let found = false; Object.keys(funcOperators).forEach((key) => { if (key === type) found = true; if (found) amount = funcOperatorskey as 'd' | 'm' | 'y'; }); } } const date = new MyDate(2021, 1, 1); console.log(date.printFormattedDate()); date.add(365, 'd'); date.add(12, 'm'); date.add(1, 'y'); console.log(date.printFormattedDate()); ```export class MyDate { year: number; month: number; day: number;   constructor(year: number, month: number, day: number) { this.year = year; this.month = month; this.day = day; }   printFormattedDate(): string { return `${this.year}/${this.month}/${this.day}`; }   add(amount: number, type: 'd' | 'm' | 'y') { const funcOperators = { d: (amount: number) => { this.day += amount; if (this.day > 30) this.day = this.day % 365 % 30;   return Math.floor(amount / 30); }, m: (amount: number) => { this.month += amount; if (this.month > 12) this.month = this.month % 12;   return Math.floor(amount / 12); }, y: (amount: number) => { this.year += amount; return 0; }, };   let found = false; Object.keys(funcOperators).forEach((key) => { if (key === type) found = true; if (found) amount = funcOperators\[key as 'd' | 'm' | 'y']\(amount); }); }} const date = new MyDate(2021, 1, 1);console.log(date.printFormattedDate());date.add(365, 'd');date.add(12, 'm');date.add(1, 'y');console.log(date.printFormattedDate());
" Los metodos definen el comportamiento de los objetos."
Solución tomando en cuenta los meses de 30 días:
addDate(amount: number, type: 'YY' | 'DD' | 'MM') { if (type === 'DD') { this.day += amount; if (this.day > 30) { this.day -= 30; this.month += 1; } } if (type === 'MM') { this.month += amount; if (this.month > 12) { this.month -= 11; this.year += 1; } } if (type === 'YY') { this.year += amount; } return `${this.year}/${this.month}/${this.day}`; } }
class MyDate { year: number; month: number; day: number; constructor(year: number, month: number, day: number) { this.year = year; this.month = month; this.day = day; } printFormat(): string { return `${this.day}/${this.month}/${this.year}`; } add(amount: number, type: 'days' | 'months' | 'years') { if (type === 'days') { if (amount < 31) { this.day += amount; } else if (amount >= 31) { amount = 1; this.day = amount; this.month += amount; } } else if (type === 'months') { if (amount < 12) { this.month += amount; } else if (amount >= 12) { amount = 1; this.year += amount; this.day = amount; this.month = amount; } } else if (type === 'years') { this.year += amount; } } } const myDate = new MyDate(2002, 4, 10); console.log('Date =>', myDate.printFormat()); myDate.add(2, 'days'); console.log('Date =>', myDate.printFormat()); myDate.add(31, 'days'); console.log('Date =>', myDate.printFormat()); myDate.add(11, 'months'); console.log('Date =>', myDate.printFormat()); myDate.add(12, 'months'); console.log('Date =>', myDate.printFormat());
Este fue lo que me puse a implementar, hice una validacion para que al momento de crear una fecha el mes no sea mayor a 12 y dia no sea mayor a 31 solo para implementar algo de innovacion al codigo.
Tambien aproveche de usar el inusable switch y agregar logica de suma de dias, meses y years:
${this.day}-${this.month}-${this.year}; }
add(amount: number, type: 'days' | 'months' | 'years') { if(type === 'days') { this.day += amount; } if(type === 'months') { this.month += amount; } if(type === 'years') { this.year += amount; }
const newyear = () => { if(this.month === 13) { this.month = 1; this.year += 1; } return this; } if(this.day === 32) { this.day = 1; this.month += 1; newyear(); } }; }
const dte = new Dte(2022, 12, 31);dte.add(1, 'days');console.log(dte.toString());
Para hacer el add mas eficiente y escalable
add(amount: number, type: 'day' | 'month' | 'year'){
if (['day', 'month', 'year'].includes(type)) { this[type] += amount; } else {
throw new Error('Invalid type provided'); } }
Mi solución:
export class MyDate{ year: number; month: number; day: number;
constructor(year: number,month: number,day: number){ this.year= year; this.month =month; this.day = day; }
printFormat(): string{
return ${this.day}/${this.month}/${this.year};
}
add(amount: number, type: 'days'|'months'|'years'){
if(type==='days'){
if (this.month == 12) {
let diaMayor = 31;
let diasRestantes = diaMayor - this.day;
let diferencia = amount - diasRestantes
if(diferencia != 0 ){
this.day -= this.day;
this.day += diferencia;
this.month=0
this.month+=1;
this.year+=1;
}
if(diferencia==0){
this.day += amount ;
}
if(diferencia >=32){
this.day = diferencia - diaMayor;
this.day =this.day + 1;
// this.month=0
this.month+=1;
return this.day ;
}
return this.day;
return this.month;
return this.year
} if (this.month == 2) { let diaMayor = 28; let diasRestantes = diaMayor - this.day; let diferencia = amount - diasRestantes if(diferencia != 0 ){ this.day -= this.day; this.day += diferencia; this.month+=1; } if(diferencia==0){ this.day += amount ; } if(diferencia >=29){ this.day = diferencia - diaMayor; this.day =this.day + 1; this.month+=2; return this.day ; } return this.day; return this.month; return this.year } if(this.month==12 && this.day<31){ let diaMayor=31; let diasRestantes = diaMayor - this.day; let diferencia = amount - diasRestantes if(diferencia != 0 ){ this.day -= this.day; this.day += diferencia; this.month=0; this.month+=1; this.year +=1; } if(diferencia==0){ this.day += amount ; } if(diferencia >=32){ this.day = diferencia - diaMayor; this.day =this.day + 1; this.month+=2; return this.day ; } return this.day; return this.month; return this.year } let diaMayor=31; let diasRestantes = diaMayor - this.day; let diferencia = amount - diasRestantes console.log(diaMayor,diasRestantes,diferencia,this.day); if(diferencia > 0){ if(diferencia >=32){ this.day = diferencia - diaMayor; this.day =this.day + 1; this.month+=2; return this.day ; } if(diferencia != 0 ){ this.day -= this.day; this.day += diferencia; this.month+=1; } if(diasRestantes == 0){ this.day =0; this.day + amount; this.month +=0 } if (this.month==12 && this.day>=31) { this.day = 0 this.month = 0; this.month +=1 this.year += 1 this.day += amount; } }else if(diferencia < 0){ this.day += amount; } } if(type==='months'){ if(this.month>=12){ this.year += 1; for (let index = 0; this.month>=12; index++) { this.month = 0; this.month+=1; } return this.month; } this.month+=amount; } if(type==='years'){ this.year+=amount; }
} } const myDate = new MyDate(2020,2,25);
console.log('Mi fecha de nacimiento es: ' ,myDate.printFormat());
myDate.add(10,'days');
console.log('Mi fecha final1 es: ', myDate.printFormat()); const myDate2 = new MyDate(2020,2,25); myDate2.add(10,'months');
console.log('Mi fecha final2 es: ', myDate2.printFormat()); const myDate3 = new MyDate(2020,2,25); myDate3.add(10,'years');
console.log('Mi fecha final3 es: ', myDate3.printFormat());
export class MyDate { year : number; month: number; day: number; constructor(year: number, month: number, day: number) { this.year = year; this.month = month; this.day = day; } monthArray = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] printFormat(): string { return `${this.day}-${this.monthArray[this.month]}-${this.year}`; } add(amount: number, type: 'day' | 'month' | 'year') { this[type]+= amount; return this.printFormat(); } } const date = new MyDate(2013,11, 6); console.log(date.printFormat()); // 6-December-2013 console.log(date.add(-4, 'month')); // 6-August-2013
Esta es mi propuesta de solución, por su puesto puede mejorar:
export enum DateEnum { Days = 'days', Months = 'months', Years = 'years', } export class MyDate { year: number; month: number; day: number; constructor(year: number, month: number, day: number) { this.year = year; this.month = month; this.day = day; } printFormat(): string { return `${this.year}/${this.month}/${this.day}`; } add(amount: number, type: DateEnum) { if (type === DateEnum.Years) { this.year += amount; } if (type === DateEnum.Months) { if (this.month + amount > 12) { // contabiliza la cantidad de años que pueden ser con los meses disponibles this.year = this.month + amount / 12; // calcula los meses puros que se agregan a la cuenta de meses this.month = this.month + (amount % 12) * 12; } else { this.month += amount; } } if (type === DateEnum.Days) { let pendingDays: number; // valida si es un año bisiesto if ( this.year % 4 === 0 || (this.year % 100 === 0 && this.year % 400 === 0 && this.day + amount > 365) ) { this.year = (this.day + amount) / 366; pendingDays = amount - 366; while (pendingDays > 0) { // calcula para febrero if (this.month === 2) { if (this.day + amount > 29) { this.month = this.month + 1; pendingDays = amount - 29; } else { this.day = this.day + amount; pendingDays = pendingDays - amount; } } // calcula para meses de 31 días else if ([1, 3, 5, 6, 7, 8, 10, 12].includes(this.month)) { if (this.day + amount > 31) { this.month = this.month + 1; pendingDays = amount - 31; } else { this.day = this.day + amount; pendingDays = pendingDays - amount; } } // calcula para meses de 30 días else { if (this.day + amount > 30) { this.month = this.month + 1; pendingDays = amount - 30; } else { this.day = this.day + amount; pendingDays = pendingDays - amount; } } } } // calcula si es un año no bisiesto o normal else if ( this.year % 4 !== 0 || (this.year % 100 !== 0 && this.year % 400 !== 0 && this.day + amount > 365) ) { this.year = (this.day + amount) / 365; pendingDays = amount - 365; while (pendingDays > 0) { // calcula para febrero if (this.month === 2) { if (this.day + amount > 28) { this.month = this.month + 1; pendingDays = amount - 28; } else { this.day = this.day + amount; pendingDays = pendingDays - amount; } } // calcula para meses de 31 días else if ([1, 3, 5, 6, 7, 8, 10, 12].includes(this.month)) { if (this.day + amount > 31) { this.month = this.month + 1; pendingDays = amount - 31; } else { this.day = this.day + amount; pendingDays = pendingDays - amount; } } // calcula para meses de 30 días else { if (this.day + amount > 30) { this.month = this.month + 1; pendingDays = amount - 30; } else { this.day = this.day + amount; pendingDays = pendingDays - amount; } } } } this.day += amount; } } } const myDate = new MyDate(1993, 7, 9); console.log(myDate.printFormat()); myDate.add(3, DateEnum.Days); console.log(myDate.printFormat()); myDate.add(3, DateEnum.Months); console.log(myDate.printFormat()); console.log(myDate.year); console.log(myDate.month); console.log(myDate.day);
Cuando resulta mas conveniente usar clases sobre usar funciones?
Las clases son para usarse como moldes cuando necesites crear muchas veces una programación o una programación muy similar vas a poder reutilizar las clases, las funciones se usan para cosas más específicas como convertir un string a entero o sumar dos números, cosas menos complejas
¿Qué es un método?
Un método es como una acción que puede hacer un objeto. Es una función que vive dentro de una clase y le dice al objeto qué hacer.
De esta manera se puede validar si llegamos a un mes máximo se suma el año y un día máximo se suma mes.
Los constructores son los que definen los parámetros de la clase. Es decir, cuando creamos una instancia los argumentos que le pasamos van dirigidos al constructor y luego esos parámetros guardados en los atributos se utilizan en los métodos de la clase.
Corriganme si estoy mal o entendí mal.
Según lo que que entiendo, el constructor es un método especial donde se inicializan los parármetros de de la clase , cuando se irealiza una nueva instancia se llama automaticamente el constructor para inicializar dichos parametros de la clase con los valores proporcionados por la nueva instancia y así ya se puede usar en los demás métodos de la clase. En el constructor no necesariamente se tienen que inicializar los parámetros, se pueden inicializar al declararlos o en otros métodos tmbien los constructores como un método tiene su visibilidad
excelente video