This repository has been archived by the owner on Mar 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (55 loc) · 1.74 KB
/
index.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
function isEmptyObject(obj) {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
function scheduleOverlaps(schedule, baseDate, offset) {
const date = new Date(baseDate);
if (offset) {
date.setUTCMinutes(date.getUTCMinutes() - offset);
}
const mapping = {
minute: date.getUTCMinutes(),
hour: date.getUTCHours(),
dayOfWeek: date.getUTCDay(),
dayOfMonth: date.getUTCDate(),
month: date.getUTCMonth(),
year: date.getUTCFullYear(),
};
for (const key in mapping) {
if (key in schedule && schedule[key] !== mapping[key]) {
return false;
}
}
return true;
}
function initialize(entries, getOffset) {
let lastChecked = new Date();
let lastOffset = getOffset ? getOffset(lastChecked) : 0;
function checkEntries() {
const currentDate = new Date();
const currentOffset = getOffset ? getOffset(currentDate) : 0;
for (const entry of entries) {
if (!entry.schedule) {
entry.action(currentDate);
} else {
const overlappedThen = scheduleOverlaps(entry.schedule, lastChecked, lastOffset);
const overlapsNow = scheduleOverlaps(entry.schedule, currentDate, currentOffset);
if (!overlappedThen && overlapsNow) {
entry.action(currentDate);
}
}
}
lastChecked = currentDate;
lastOffset = currentOffset;
scheduleCheckEntries();
}
function scheduleCheckEntries() {
const currentDate = new Date();
const nextDate = new Date(currentDate);
nextDate.setUTCMinutes(nextDate.getUTCMinutes() + 1);
nextDate.setUTCSeconds(0);
nextDate.setUTCMilliseconds(0);
setTimeout(checkEntries, nextDate - currentDate);
}
scheduleCheckEntries();
}
module.exports = { scheduleOverlaps, initialize };