No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Aprende Inglés, Programación, AI, Ciberseguridad y más a precio especial.

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
2 Hrs
18 Min
22 Seg

Métodos

3/25
Recursos

Aportes 16

Preguntas 1

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

Entendí que:
métodos => Funciones dentro de una clase.
propiedades ó atributos => Variables (ó constantes) dentro de una clase.

Les comparto mis apuntes. 😄

¿Qué hacen los métodos?

Describen el comportamiento de los objetos.

Sintaxis

class nameClass {
		constructor (parameters) { statements }

		methodName (parameters: dataTypes): dataType { statements }
}

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'));

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));
  };

" 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}`;
  }
}
¿Y si añado por ejemplo 100 días o 24 meses? ... si se lo preguntaron aquí está el código: ```js 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()); ```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());

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

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.

![](https://static.platzi.com/media/user_upload/image-5b4c37a5-f02e-4fb4-b607-74b9f365fa34.jpg)class Dte {    year: number;    month: number;    day: number;        constructor(*year*: number, *month*: number, *day*: number) {        this.year = *year*;        this.month = *month*;        this.day = *day*;    }     toString(): string {        return `${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()); ![]()![](https://static.platzi.com/media/user_upload/image-a802e2d9-8b17-46e2-aba3-c0c4b294408e.jpg)![](https://static.platzi.com/media/user_upload/image-ad4cf1b8-39c1-4932-9905-f93074d68b84.jpg)
![](https://static.platzi.com/media/user_upload/image-c0b2d62c-8b68-4c1a-89c6-7566b89ac6fe.jpg)
excelente video

Esta libreria es muy util para fechas y monedas… 100% recomendada. https://www.npmjs.com/package/moment

Ah cierto y un constructor, como su nombre lo indica es la parte dinamica que construye la clase en base a los parametros que le enviemos, Dios mio podemos tipar esos parametros, y obligarnos a hacer que todo funcione correctooo! ts lo mejor en js💙💛

Basicamente las clases son objetos que instanciamos en nuestro programa, y dentro de ese cool objeto existen funciones que desempeñan un rol en especifico aunque por estar dentro de una clase, la llamamos métodos