-
-
Notifications
You must be signed in to change notification settings - Fork 161
/
Copy pathclock.example.ts
62 lines (48 loc) · 1.54 KB
/
clock.example.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
export default class Clock {
private hour!: number
private minute!: number
constructor(hour: number, minute: number = 0) {
this.reset()
const totalMinutes = hour * 60 + minute
this.adjustTime(totalMinutes)
}
private reset(): void {
this.hour = 0
this.minute = 0
}
public getHour(): number {
return this.hour
}
public getMinute(): number {
return this.minute
}
public toString(): string {
return `${this.formatNumber(this.hour)}:${this.formatNumber(this.minute)}`
}
private formatNumber(numberToFormat: number): string {
const numberString = numberToFormat.toString()
return numberString.length === 1 ? `0${numberString}` : numberString
}
public plus(minutes: number): Clock {
this.adjustTime(minutes)
return this
}
public minus(minutes: number): Clock {
this.adjustTime(-1 * minutes)
return this
}
public equals(clock: Clock): boolean {
return this.hour === clock.getHour() && this.minute === clock.getMinute()
}
private adjustTime(delta: number): void {
const minutesPerDay = 1440
const minutesPerHour = 60
const hoursPerDay = 24
delta = Math.abs(delta) >= minutesPerDay ? delta % minutesPerDay : delta
const currentMinutes = this.hour * minutesPerHour + this.minute
let newMinutes = (currentMinutes + delta) % minutesPerDay
newMinutes = newMinutes < 0 ? newMinutes += minutesPerDay : newMinutes
this.hour = Math.floor(newMinutes / minutesPerHour) % hoursPerDay
this.minute = newMinutes - this.hour * minutesPerHour
}
}