Acceso privado

5/25
Recursos

Aportes 4

Preguntas 0

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad? Crea una cuenta o inicia sesión.

¿Qué quiere decir?

Podemos proteger nuestras propiedades y métodos para que nos sean accedidos y modificados por fuera de clase.

Private

Con esta palabra reservada private estamos restringiendo el acceso de nuestros parámetros y métodos, solo podrán ser accedidos o modificados dentro de la clase.

Sintaxis

class nameClass {
		private parameter1: dataType;
		constructor (parameters) { statements }

		private method (parameters): dataType { statements }
}

Private class fields (#)

A desde hace muy poco JavaScript tiene incorporado la capacidad de poder limitar el alcance de los métodos y propiedades utilizando #. Funciona igual que private, solo que # es nativo de JavaScript y realmente limita el alcance.

Sintaxis

class nameClass {
		#parameter1: dataType;
		constructor (parameters) { statements }

		#method (parameters): dataType { statements }
}

Ejemplo

type PartOfTheCalendar = 'day' | 'month'| 'year';

export class MyDate {
    year: number;
    private month: number;
    #day: number;

    constructor (year: number, month: number, day: number) {
        this.year = year;
        this.month = month;
        this.#day = day;
    }

    printFormat (): string {
        const { year } = this;
        const day = this.#addPadding(this.#day);
        const month = this.#addPadding(this.month);
        return `${day}/${month}/${year}`;
    }

    add (amount: number, type: PartOfTheCalendar) {
        if (type === 'day') this.#day += amount;
        if (type === 'month') this.month += amount;
        if (type === 'year') this. year += amount;
    }

    #addPadding (value: number) {
        if (value < 10) return `0${value}`;
        return `${value}`;
    }

    //  private addPadding (value: number) {
    //     if (value < 10) return `0${value}`;
    //     return `${value}`;
    // }
}
private addMonth(months: number = 1): string {
    this._month += months;
    while (this.month > 12) {
      this.addYear();
      this._month -= 12;
    }
    return this.printFormat();
  }
  private addYear(years: number = 1) {
    this._year += years;
    return this.printFormat();
  }
  private addDay(days: number = 1): string {
    const daysPerMonth: number = 30;
    this._day += days;
    while (this.day > daysPerMonth) {
      this.addMonth();
      this._day -= daysPerMonth;
    }
    return this.printFormat();
  }
  get day(): number {
    return this._day;
  }
  get month(): number {
    return this._month;
  }
  get year(): number {
    return this._year;
  }
  add(amount: number, type: "days" | "years" | "months"): string | void {
    if (typeof amount === "number") {
      switch (type) {
        case "days":
          return this.addDay(amount);
        case "years":
          return this.addYear(amount);
        case "months":
          return this.addMonth(amount);
        default:
          return console.error("El tipo no existe");
      }
    }
    return console.error("amount debe ser un number");
  }

Dejo mi solucion

export type formatDate = 'days' | 'months' | 'years';

class MyDate {
    private _year: number;
    private _month: number;
    private _day: number;
    private _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._validLeapYear()
        this._month = this._validMonth(month);
        this._day = this._validDay(day);
    }

    printFormat(format: string = 'dd / nm / yy'): string {
        if (this._validError() == null) { // if validError returns null then there are no errors
            let day: string = this._addPadding(this._day);
            let month: string = this._addPadding(this._month);
            format = format.replace('yy', this._year.toString());
            format = format.replace('dd', day);
            format = format.replace('mm', month);
            format = format.replace('nm', this._months[this._month]);
            return format;
        } else {
            return this._validError()!; // notation ! tells typescript that the programmer is in control
        }
    }

    // override
    toString(): string {
        return this.printFormat();
    }

    get day(): number {
        return this._day;
    }

    get month(): number {
        return this._month;
    }

    get monthName(): string {
        return this._months[this._month];
    }

    get year(): number {
        return this._year;
    }

    get leapYear(): boolean {
        return this._leapYear;
    }

    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 _addPadding(num: number): string {
        if (num < 10) {
            return `0${num}`;
        }
        return num.toString();
    }

    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 _validLeapYear() {
        /**
         * @ 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 nm of yy'));
myDate.add(3, 'days');
console.log(myDate.printFormat());
myDate.add(40, 'months');
console.log(myDate.printFormat('mm-dd-yy'));
console.log(myDate.toString());
console.log(myDate.day);
console.log(myDate.month);
console.log(myDate.monthName);
console.log(myDate.year);
El acceso privado a los atributos y métodos nos permite restringir la modificación no autorizada a los datos de la clase, y de esta manera tener más control sobre nuestra clase.