export class CronHelper { protected static cronStringToCronObject(str: string | null): { ranges: Array> | null; value: number | null; values: Array | null; } | null { if (!str) { return null; } if (str === '*') { return null; } if (str.includes(',')) { return { ranges: null, value: null, values: str.split(',').map((x) => CronHelper.cronStringToCronObject(x)), }; } if (str.includes('-')) { const strSplitted: Array = str.split('-'); return { ranges: [[parseInt(strSplitted[0]), parseInt(strSplitted[1])]], value: null, values: null, }; } if (str.includes('/')) { return null; } return { ranges: null, value: parseInt(str), values: null, }; } public static matchCurrentTimestamp( cron: string | null, timestamp: number | null ): boolean { if (!timestamp) { return false; } if (!cron) { return false; } const cronSplitted: Array = cron.split(' '); if (cronSplitted.length !== 5) { return false; } // minute hour date month day const minute = CronHelper.cronStringToCronObject(cronSplitted[0]); const hour = CronHelper.cronStringToCronObject(cronSplitted[1]); const date = CronHelper.cronStringToCronObject(cronSplitted[2]); const month = CronHelper.cronStringToCronObject(cronSplitted[3]); const day = CronHelper.cronStringToCronObject(cronSplitted[4]); if (!CronHelper.validCronObject(minute, new Date(timestamp).getMinutes())) { return false; } if (!CronHelper.validCronObject(hour, new Date(timestamp).getHours())) { return false; } if (!CronHelper.validCronObject(date, new Date().getDate())) { return false; } if (!CronHelper.validCronObject(month, new Date(timestamp).getMonth())) { return false; } if (!CronHelper.validCronObject(day, new Date(timestamp).getDay())) { return false; } return true; } protected static validCronObject( obj: { ranges: Array> | null; value: number | null; values: Array | null; } | null, value: number | null ): boolean { if (!obj) { return true; } if ( obj.values && obj.values.filter((x) => CronHelper.validCronObject(x, value)).length === 0 ) { return false; } if (obj.value && obj.value !== value) { return false; } if (obj.ranges) { for (const range of obj.ranges) { if (value && value >= range[0] && value <= range[1]) { return true; } } return false; } return true; } }