/lib/cron.time.js
https://github.com/podviaznikov/cron · JavaScript · 77 lines · 57 code · 17 blank · 3 comment · 4 complexity · 1365cf0e78218ef28bb4c2fe445e2c63 MD5 · raw file
- var CronTime = exports.CronTime = function CronTime(time){
- this.source = time;
- this.map= ['second', 'minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];
- this.constraints = [[0,59],[0,59],[0,23],[1,31],[0,11],[1,7]];
- this.aliases = {
- jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12,
- sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6
- };
- this.second = {};
- this.minute = {};
- this.hour = {};
- this.dayOfMonth = {};
- this.month = {};
- this.dayOfWeek = {};
- this._parse();
- }
- CronTime.prototype = {
- _parse: function(){
- var aliases = this.aliases,
- cur,
- len=6;
- var source = this.source.replace(/[a-z]/i, function(alias){
- alias = alias.toLowerCase();
- if(alias in aliases){
- return aliases[alias];
- }
- throw new Error('Unknown alias: ' + alias);
- });
- var split = this.source.replace(/^\s\s*|\s\s*$/g, '').split(/\s+/);
- while(len--){
- cur = split[len] || '*';
- this._parseField(cur, this.map[len], this.constraints[len]);
- }
- },
- _parseField: function(field, type, constraints){
- var rangePattern = /(\d+?)(?:-(\d+?))?(?:\/(\d+?))?(?:,|$)/g,
- typeObj = this[type],
- diff,
- low = constraints[0],
- high = constraints[1];
- // * is a shortcut to [lower-upper] range
- field = field.replace(/\*/g, low + '-' + high);
- if(field.match(rangePattern)){
- field.replace(rangePattern, function($0, lower, upper, step){
- step = step || 1;
- // Positive integer higher than constraints[0]
- lower = Math.max(low, ~~Math.abs(lower));
- // Positive integer lower than constraints[1]
- upper = upper ? Math.min(high, ~~Math.abs(upper)) : lower;
- diff = step+upper-lower;
- while((diff -= step) > -1){
- typeObj[diff+lower] = true;
- }
- });
- }
- else{
- throw new Error('Field (' + field + ') cannot be parsed');
- }
- }
- };