refactor: set readonly ticks

This commit is contained in:
Polianin Nikita 2024-06-10 21:44:41 +03:00
parent 2e4b1ec876
commit c5f4b7b526

View File

@ -1,42 +1,36 @@
export class DateOnly { export class DateOnly {
private ticks: number; private readonly _ticks: number;
/*
constructor(year: number, month: number, day: number) {
this.ticks = new Date(year, month - 1, day).getTime();
}
*/
constructor(year: number, month: number, day: number); constructor(year: number, month: number, day: number);
constructor(date: Date); constructor(date: Date);
constructor(date: string); constructor(date: string);
constructor(yearOrDate: number | Date | string, month?: number, day?: number) { constructor(yearOrDate: number | Date | string, month?: number, day?: number) {
if (yearOrDate instanceof Date) { if (yearOrDate instanceof Date) {
this.ticks = yearOrDate.getTime(); this._ticks = yearOrDate.getTime();
} else if (typeof yearOrDate === 'number' && month !== undefined && day !== undefined) { } else if (typeof yearOrDate === 'number' && month !== undefined && day !== undefined) {
this.ticks = new Date(yearOrDate, month - 1, day).getTime(); this._ticks = new Date(yearOrDate, month - 1, day).getTime();
} else if (typeof yearOrDate === 'string') { } else if (typeof yearOrDate === 'string') {
const [year, month, day] = yearOrDate.split('-').map(Number); const [year, month, day] = yearOrDate.split('-').map(Number);
this.ticks = new Date(year, month - 1, day).getTime(); this._ticks = new Date(year, month - 1, day).getTime();
} else { } else {
throw new Error('Invalid constructor arguments'); throw new Error('Invalid constructor arguments');
} }
} }
get year(): number { get year(): number {
return new Date(this.ticks).getFullYear(); return new Date(this._ticks).getFullYear();
} }
get month(): number { get month(): number {
return new Date(this.ticks).getMonth() + 1; return new Date(this._ticks).getMonth() + 1;
} }
get day(): number { get day(): number {
return new Date(this.ticks).getDate(); return new Date(this._ticks).getDate();
} }
get date(): Date { get date(): Date {
return new Date(this.ticks); return new Date(this._ticks);
} }
toString(): string { toString(): string {