forked from netology-code/bjs-homeworks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtask.js
115 lines (100 loc) · 2.51 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
'use strict'
class AlarmClock {
alarmCollection;
timerId;
constructor() {
this.alarmCollection = [];
this.timerId = null;
}
addClock(time, callback, id) {
if (!id) {
throw new Error('Необходим идентификатор создаваемого звонка');
}
if ( this.alarmCollection.some( alarm => alarm.id === id ) ) {
console.error(`Будильник с таким идентификатором уже существует!
Новый будильник не добавлен!`);
} else {
this.alarmCollection.push({ id, time, callback });
}
}
removeClock(id) {
const oldLength = this.alarmCollection.length;
this.alarmCollection = this.alarmCollection.filter( alarm => alarm.id !== id );
return oldLength !== this.alarmCollection;
}
getCurrentFormattedTime(shift = 0) {
let time = new Date();
time.setMinutes(time.getMinutes() + shift);
let h = time.getHours();
if (h < 10) {
h = '0' + h;
}
let m = time.getMinutes();
if (m < 10) {
m = '0' + m;
}
return `${h}:${m}`;
}
start() {
if (this.timerId) {
return;
}
this.timerId = setInterval(
() => this.alarmCollection.forEach(
alarm => checkClock.call(this, alarm)
), //норм так раскидывать каждый callback на новую строку?
1000
);
function checkClock(alarm) {
if (alarm.time === this.getCurrentFormattedTime()) {
alarm.callback();
}
}
}
stop() {
if (this.timerId) {
clearInterval(this.timerId);
this.timerId = null; //или лучше delete this.timerId
}
}
printAlarms() {
this.alarmCollection.forEach( alarm => console.log(`${alarm.id} ${alarm.time}`) );
}
clearAlarms() {
this.stop();
this.alarmCollection = [];
}
}
let alarms;
function testCase() {
alarms = new AlarmClock();
function alarmLog() {
console.log(`alarm ${this.time}`);
}
alarms.addClock(
alarms.getCurrentFormattedTime(),
alarmLog,
1
);
alarms.addClock(
alarms.getCurrentFormattedTime(1),
function () {
alarmLog.call(this);
alarms.removeClock(this.id);
},
2
);
alarms.addClock(
alarms.getCurrentFormattedTime(2),
function () {
alarmLog.call(this);
console.log('before clearing');
alarms.printAlarms();
alarms.clearAlarms();
console.log('after clearing');
alarms.printAlarms();
},
3
);
alarms.start();
}