CursosEmpresasBlogLiveConfPrecios

Métodos

Clase 3 de 25 • Curso de TypeScript: Programación Orientada a Objetos y Asincronismo

Contenido del curso

Introducción

  • 1
    ¿Ya tomaste el Curso de TypeScript: Tipos Avanzados y Funciones?

    ¿Ya tomaste el Curso de TypeScript: Tipos Avanzados y Funciones?

    05:16 min

Fundamentos de POO

  • 2
    Class

    Class

    12:19 min
  • 3
    Métodos

    Métodos

    Viendo ahora
  • 4
    Acceso público

    Acceso público

    05:16 min
  • 5
    Acceso privado

    Acceso privado

    10:20 min
  • 6
    Constructor

    Constructor

    08:00 min
  • 7
    Getters

    Getters

    11:48 min
  • 8
    Setters

    Setters

    07:55 min

POO Avanzada

  • 9
    Herencia

    Herencia

    10:18 min
  • 10
    Acceso protegido

    Acceso protegido

    08:02 min
  • 11
    Static

    Static

    12:01 min
  • 12
    Interfaces

    Interfaces

    13:45 min
  • 13
    Clases abstractas

    Clases abstractas

    06:14 min
  • 14
    Singleton: constructor privado

    Singleton: constructor privado

    10:36 min

Asincronismo y consumo de APIs

  • 15
    Promesas

    Promesas

    14:13 min
  • 16
    Tipando respuestas HTTP

    Tipando respuestas HTTP

    11:38 min
  • 17
    Proyecto: migración de funciones a clases

    Proyecto: migración de funciones a clases

    10:05 min
  • 18
    Consumiendo ProductMemoryService

    Consumiendo ProductMemoryService

    06:30 min
  • 19
    ProductHttpService

    ProductHttpService

    15:33 min
  • 20
    Consumiendo ProductHttpService

    Consumiendo ProductHttpService

    09:22 min

Genéricos

  • 21
    Generics

    Generics

    10:22 min
  • 22
    Generics en clases

    Generics en clases

    12:08 min
  • 23
    Generics en métodos

    Generics en métodos

    15:11 min
  • 24
    Decoradores

    Decoradores

    15:05 min

Próximos pasos

  • 25
    ¿Quieres más cursos de TypeScript?

    ¿Quieres más cursos de TypeScript?

    01:20 min
Tomar examen

Escuelas

  • Desarrollo Web
    • Fundamentos del Desarrollo Web Profesional
    • Diseño y Desarrollo Frontend
    • Desarrollo Frontend con JavaScript
    • Desarrollo Frontend con Vue.js
    • Desarrollo Frontend con Angular
    • Desarrollo Frontend con React.js
    • Desarrollo Backend con Node.js
    • Desarrollo Backend con Python
    • Desarrollo Backend con Java
    • Desarrollo Backend con PHP
    • Desarrollo Backend con Ruby
    • Bases de Datos para Web
    • Seguridad Web & API
    • Testing Automatizado y QA para Web
    • Arquitecturas Web Modernas y Escalabilidad
    • DevOps y Cloud para Desarrolladores Web
  • English Academy
    • Inglés Básico A1
    • Inglés Básico A2
    • Inglés Intermedio B1
    • Inglés Intermedio Alto B2
    • Inglés Avanzado C1
    • Inglés para Propósitos Específicos
    • Inglés de Negocios
  • Marketing Digital
    • Fundamentos de Marketing Digital
    • Marketing de Contenidos y Redacción Persuasiva
    • SEO y Posicionamiento Web
    • Social Media Marketing y Community Management
    • Publicidad Digital y Paid Media
    • Analítica Digital y Optimización (CRO)
    • Estrategia de Marketing y Growth
    • Marketing de Marca y Comunicación Estratégica
    • Marketing para E-commerce
    • Marketing B2B
    • Inteligencia Artificial Aplicada al Marketing
    • Automatización del Marketing
    • Marca Personal y Marketing Freelance
    • Ventas y Experiencia del Cliente
    • Creación de Contenido para Redes Sociales
  • Inteligencia Artificial y Data Science
    • Fundamentos de Data Science y AI
    • Análisis y Visualización de Datos
    • Machine Learning y Deep Learning
    • Data Engineer
    • Inteligencia Artificial para la Productividad
    • Desarrollo de Aplicaciones con IA
    • AI Software Engineer
  • Ciberseguridad
    • Fundamentos de Ciberseguridad
    • Hacking Ético y Pentesting (Red Team)
    • Análisis de Malware e Ingeniería Forense
    • Seguridad Defensiva y Cumplimiento (Blue Team)
    • Ciberseguridad Estratégica
  • Liderazgo y Habilidades Blandas
    • Fundamentos de Habilidades Profesionales
    • Liderazgo y Gestión de Equipos
    • Comunicación Avanzada y Oratoria
    • Negociación y Resolución de Conflictos
    • Inteligencia Emocional y Autogestión
    • Productividad y Herramientas Digitales
    • Gestión de Proyectos y Metodologías Ágiles
    • Desarrollo de Carrera y Marca Personal
    • Diversidad, Inclusión y Entorno Laboral Saludable
    • Filosofía y Estrategia para Líderes
  • Diseño de Producto y UX
    • Fundamentos de Diseño UX/UI
    • Investigación de Usuarios (UX Research)
    • Arquitectura de Información y Usabilidad
    • Diseño de Interfaces y Prototipado (UI Design)
    • Sistemas de Diseño y DesignOps
    • Redacción UX (UX Writing)
    • Creatividad e Innovación en Diseño
    • Diseño Accesible e Inclusivo
    • Diseño Asistido por Inteligencia Artificial
    • Gestión de Producto y Liderazgo en Diseño
    • Diseño de Interacciones Emergentes (VUI/VR)
    • Desarrollo Web para Diseñadores
    • Diseño y Prototipado No-Code
  • Contenido Audiovisual
    • Fundamentos de Producción Audiovisual
    • Producción de Video para Plataformas Digitales
    • Producción de Audio y Podcast
    • Fotografía y Diseño Gráfico para Contenido Digital
    • Motion Graphics y Animación
    • Contenido Interactivo y Realidad Aumentada
    • Estrategia, Marketing y Monetización de Contenidos
  • Desarrollo Móvil
    • Fundamentos de Desarrollo Móvil
    • Desarrollo Nativo Android con Kotlin
    • Desarrollo Nativo iOS con Swift
    • Desarrollo Multiplataforma con React Native
    • Desarrollo Multiplataforma con Flutter
    • Arquitectura y Patrones de Diseño Móvil
    • Integración de APIs y Persistencia Móvil
    • Testing y Despliegue en Móvil
    • Diseño UX/UI para Móviles
  • Diseño Gráfico y Arte Digital
    • Fundamentos del Diseño Gráfico y Digital
    • Diseño de Identidad Visual y Branding
    • Ilustración Digital y Arte Conceptual
    • Diseño Editorial y de Empaques
    • Motion Graphics y Animación 3D
    • Diseño Gráfico Asistido por Inteligencia Artificial
    • Creatividad e Innovación en Diseño
  • Programación
    • Fundamentos de Programación e Ingeniería de Software
    • Herramientas de IA para el trabajo
    • Matemáticas para Programación
    • Programación con Python
    • Programación con JavaScript
    • Programación con TypeScript
    • Programación Orientada a Objetos con Java
    • Desarrollo con C# y .NET
    • Programación con PHP
    • Programación con Go y Rust
    • Programación Móvil con Swift y Kotlin
    • Programación con C y C++
    • Administración Básica de Servidores Linux
  • Negocios
    • Fundamentos de Negocios y Emprendimiento
    • Estrategia y Crecimiento Empresarial
    • Finanzas Personales y Corporativas
    • Inversión en Mercados Financieros
    • Ventas, CRM y Experiencia del Cliente
    • Operaciones, Logística y E-commerce
    • Gestión de Proyectos y Metodologías Ágiles
    • Aspectos Legales y Cumplimiento
    • Habilidades Directivas y Crecimiento Profesional
    • Diversidad e Inclusión en el Entorno Laboral
    • Herramientas Digitales y Automatización para Negocios
  • Blockchain y Web3
    • Fundamentos de Blockchain y Web3
    • Desarrollo de Smart Contracts y dApps
    • Finanzas Descentralizadas (DeFi)
    • NFTs y Economía de Creadores
    • Seguridad Blockchain
    • Ecosistemas Blockchain Alternativos (No-EVM)
    • Producto, Marketing y Legal en Web3
  • Recursos Humanos
    • Fundamentos y Cultura Organizacional en RRHH
    • Atracción y Selección de Talento
    • Cultura y Employee Experience
    • Gestión y Desarrollo de Talento
    • Desarrollo y Evaluación de Liderazgo
    • Diversidad, Equidad e Inclusión
    • AI y Automatización en Recursos Humanos
    • Tecnología y Automatización en RRHH
  • Finanzas e Inversiones
    • Fundamentos de Finanzas Personales y Corporativas
    • Análisis y Valoración Financiera
    • Inversión y Mercados de Capitales
    • Finanzas Descentralizadas (DeFi) y Criptoactivos
    • Finanzas y Estrategia para Startups
    • Inteligencia Artificial Aplicada a Finanzas
    • Domina Excel
    • Financial Analyst
    • Conseguir trabajo en Finanzas e Inversiones
  • Startups
    • Fundamentos y Validación de Ideas
    • Estrategia de Negocio y Product-Market Fit
    • Desarrollo de Producto y Operaciones Lean
    • Finanzas, Legal y Fundraising
    • Marketing, Ventas y Growth para Startups
    • Cultura, Talento y Liderazgo
    • Finanzas y Operaciones en Ecommerce
    • Startups Web3 y Blockchain
    • Startups con Impacto Social
    • Expansión y Ecosistema Startup
  • Cloud Computing y DevOps
    • Fundamentos de Cloud y DevOps
    • Administración de Servidores Linux
    • Contenerización y Orquestación
    • Infraestructura como Código (IaC) y CI/CD
    • Amazon Web Services
    • Microsoft Azure
    • Serverless y Observabilidad
    • Certificaciones Cloud (Preparación)
    • Plataforma Cloud GCP

Platzi y comunidad

  • Platzi Business
  • Live Classes
  • Lanzamientos
  • Executive Program
  • Trabaja con nosotros
  • Podcast

Recursos

  • Manual de Marca

Soporte

  • Preguntas Frecuentes
  • Contáctanos

Legal

  • Términos y Condiciones
  • Privacidad
  • Tyc promociones
Reconocimientos
Reconocimientos
Logo reconocimientoTop 40 Mejores EdTech del mundo · 2024
Logo reconocimientoPrimera Startup Latina admitida en YC · 2014
Logo reconocimientoPrimera Startup EdTech · 2018
Logo reconocimientoCEO Ganador Medalla por la Educación T4 & HP · 2024
Logo reconocimientoCEO Mejor Emprendedor del año · 2024
De LATAM conpara el mundo
YoutubeInstagramLinkedInTikTokFacebookX (Twitter)Threads

      Comentarios

        William Cortes

        William Cortes

        student•
        hace 4 años

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

          Luis Ariza

          Luis Ariza

          student•
          hace 4 años

          ¡¡Entendiste bien!! 👍

          Josue Cerron Tuesta

          Josue Cerron Tuesta

          student•
          hace 3 años

          Así es bro!

        Axel Enrique Galeed Gutierrez

        Axel Enrique Galeed Gutierrez

        student•
        hace 4 años

        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 } }
          Eduardo Esteban Álvarez Castañeda

          Eduardo Esteban Álvarez Castañeda

          student•
          hace 2 años

          Ojo que una buena práctica, es crear los nombres de las clases en formato PascalCase

          Axel Enrique Galeed Gutierrez

          Axel Enrique Galeed Gutierrez

          student•
          hace 2 años

          Hola, @Proskynete, tenés toda la razón, se me escapó ese typo.

        Jordy Mairena Montoya

        Jordy Mairena Montoya

        student•
        hace 4 años

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

          Ronaldo Delgado

          student•
          hace 2 años

          Genial!

        CHRISTIAN OLIVER SOLANO NUÑEZ

        CHRISTIAN OLIVER SOLANO NUÑEZ

        student•
        hace 4 años

        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)); };
        Kevin Daniel Guzman Delgadillo

        Kevin Daniel Guzman Delgadillo

        student•
        hace 3 años

        ¿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; &#x20; constructor(year: number, month: number, day: number) { this.year = year; this.month = month; this.day = day; } &#x20; printFormattedDate(): string { return `${this.year}/${this.month}/${this.day}`; } &#x20; 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; &#x20; return Math.floor(amount / 30); }, m: (amount: number) => { this.month += amount; if (this.month > 12) this.month = this.month % 12; &#x20; return Math.floor(amount / 12); }, y: (amount: number) => { this.year += amount; return 0; }, }; &#x20; 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());
        Jesus Abel Jimenez Bracho

        Jesus Abel Jimenez Bracho

        student•
        hace 4 años

        " Los metodos definen el comportamiento de los objetos."

        Javier Alejandro Albornoz Pérez

        Javier Alejandro Albornoz Pérez

        student•
        hace 3 años

        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}`; } }
        Johan Sebastian

        Johan Sebastian

        student•
        hace 7 meses
        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());
        Kellbis Salazar

        Kellbis Salazar

        student•
        hace un año

        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:

        Victor Perozo

        Victor Perozo

        student•
        hace 2 años
        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());
        Andrés Corral

        Andrés Corral

        student•
        hace 2 años

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

        Paula Catalina Delgado Almendrales

        Paula Catalina Delgado Almendrales

        student•
        hace 4 años

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

        Jose Gregorio  Sarabia Lugo

        Jose Gregorio Sarabia Lugo

        student•
        hace 3 años
        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
        David Rangel

        David Rangel

        student•
        hace 3 meses

        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);
        Pedro Carreño

        Pedro Carreño

        student•
        hace 3 años

        Cuando resulta mas conveniente usar clases sobre usar funciones?

          Jose Ever Muñoz Muñoz

          Jose Ever Muñoz Muñoz

          student•
          hace 3 años

          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

        Valentina Hernández

        Valentina Hernández

        student•
        hace 10 meses

        ¿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.

        Juan David Marin Rodriguez

        Juan David Marin Rodriguez

        student•
        hace un año

        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.

        Diego Raciel Ortega Hernandez

        Diego Raciel Ortega Hernandez

        student•
        hace 3 años

        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.

          oscar.rusinque

          oscar.rusinque

          student•
          hace 2 años

          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

        Winslow Taylor Geldres Oliveros

        Winslow Taylor Geldres Oliveros

        student•
        hace 2 años
        Ronaldo Delgado

        Ronaldo Delgado

        student•
        hace 2 años

        excelente video