Entendí que:
métodos => Funciones dentro de una clase.
propiedades ó atributos => Variables (ó constantes) dentro de una clase.
Introducción
¿Ya tomaste el Curso de TypeScript: Tipos Avanzados y Funciones?
Fundamentos de POO
Class
Métodos
Acceso público
Acceso privado
Constructor
Getters
Setters
POO Avanzada
Herencia
Acceso protegido
Static
Interfaces
Clases abstractas
Singleton: constructor privado
Asincronismo y consumo de APIs
Promesas
Tipando respuestas HTTP
Proyecto: migración de funciones a clases
Consumiendo ProductMemoryService
ProductHttpService
Consumiendo ProductHttpService
Genéricos
Generics
Generics en clases
Generics en métodos
Decoradores
Próximos pasos
¿Quieres más cursos de TypeScript?
No tienes acceso a esta clase
¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera
Aportes 17
Preguntas 1
Entendí que:
métodos => Funciones dentro de una clase.
propiedades ó atributos => Variables (ó constantes) dentro de una clase.
Les comparto mis apuntes. 😄
Describen el comportamiento de los objetos.
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}`;
}
}
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.
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
¿Quieres ver más aportes, preguntas y respuestas de la comunidad?