/
time-matcher.js
43 lines (36 loc) · 1.52 KB
/
time-matcher.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
const validatePattern = require('./pattern-validation');
const convertExpression = require('./convert-expression');
const moment = require('moment-timezone');
function matchPattern(pattern, value){
if( pattern.indexOf(',') !== -1 ){
const patterns = pattern.split(',');
return patterns.indexOf(value.toString()) !== -1;
}
return pattern === value.toString();
}
class TimeMatcher{
constructor(pattern, timezone){
validatePattern(pattern);
this.pattern = convertExpression(pattern);
this.timezone = timezone;
this.expressions = this.pattern.split(' ');
}
match(date){
date = this.apply(date);
const runOnSecond = matchPattern(this.expressions[0], date.getSeconds());
const runOnMinute = matchPattern(this.expressions[1], date.getMinutes());
const runOnHour = matchPattern(this.expressions[2], date.getHours());
const runOnDay = matchPattern(this.expressions[3], date.getDate());
const runOnMonth = matchPattern(this.expressions[4], date.getMonth() + 1);
const runOnWeekDay = matchPattern(this.expressions[5], date.getDay());
return runOnSecond && runOnMinute && runOnHour && runOnDay && runOnMonth && runOnWeekDay;
}
apply(date){
if(this.timezone){
const tmp = moment.tz(date, this.timezone);
return new Date(tmp.year(), tmp.month(), tmp.date(), tmp.hour(), tmp.minute(), tmp.second(), tmp.millisecond());
}
return date;
}
}
module.exports = TimeMatcher;