forked from netology-code/bjs-homeworks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.js
95 lines (75 loc) · 2.48 KB
/
task.js
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
'use strict';
class AlarmClock {
constructor() {
this.alarmCollection = [];
this.timerId = null;
}
addClock(time, callback, id) {
if (!id) {
throw new Error('Невозможно идентифицировать будильник. Параметр id не передан.');
}
const sameAlarm = this.alarmCollection.find((alarm) => alarm.id === id);
if (sameAlarm) {
console.error('Будильник с таким id уже существует.');
} else {
this.alarmCollection.push({ time, callback, id });
}
}
removeClock(id) {
const index = this.alarmCollection.findIndex(
(alarm) => alarm.id === id
);
return index !== -1
? Boolean(this.alarmCollection.splice(index, 1))
: false;
}
getCurrentFormattedTime() {
return new Date()
.toLocaleTimeString('ru-RU', { hour12: false })
.substring(0, 5);
}
checkClock(clock) {
if (clock.time === this.getCurrentFormattedTime()) {
clock.callback();
}
}
start() {
if (!this.timerId) {
this.timerId = setInterval(() => {
this.alarmCollection.forEach((alarm) => this.checkClock(alarm));
}, 100);
}
}
stop() {
if (this.timerId) {
clearInterval(this.timerId);
this.timerId = null;
}
}
printAlarms() {
console.log(
`Печать всех будильников в количестве: ${this.alarmCollection.length}`
);
this.alarmCollection.forEach((alarm) =>
console.log(`Будильник №${alarm.id} заведён на ${alarm.time}`)
);
}
clearAlarms() {
this.stop();
this.alarmCollection = [];
}
}
// Sample usage
let phoneAlarm = new AlarmClock();
phoneAlarm.addClock('12:37', () => console.log('1 сентября. Вовочка приходит из школы. Папа спрашивает:'), 1);
phoneAlarm.addClock('12:38', () => {
console.log('– Ну, как тебе, Вовочка, первая учительница?');
phoneAlarm.removeClock(2);
}, 2);
phoneAlarm.addClock('12:40', () => {
console.log('– Первой была воспитательница.');
phoneAlarm.clearAlarms();
phoneAlarm.printAlarms();
}, 3);
phoneAlarm.printAlarms();
phoneAlarm.start();