/lib/cron.time.js

https://github.com/podviaznikov/cron · JavaScript · 77 lines · 57 code · 17 blank · 3 comment · 4 complexity · 1365cf0e78218ef28bb4c2fe445e2c63 MD5 · raw file

  1. var CronTime = exports.CronTime = function CronTime(time){
  2. this.source = time;
  3. this.map= ['second', 'minute', 'hour', 'dayOfMonth', 'month', 'dayOfWeek'];
  4. this.constraints = [[0,59],[0,59],[0,23],[1,31],[0,11],[1,7]];
  5. this.aliases = {
  6. jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12,
  7. sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6
  8. };
  9. this.second = {};
  10. this.minute = {};
  11. this.hour = {};
  12. this.dayOfMonth = {};
  13. this.month = {};
  14. this.dayOfWeek = {};
  15. this._parse();
  16. }
  17. CronTime.prototype = {
  18. _parse: function(){
  19. var aliases = this.aliases,
  20. cur,
  21. len=6;
  22. var source = this.source.replace(/[a-z]/i, function(alias){
  23. alias = alias.toLowerCase();
  24. if(alias in aliases){
  25. return aliases[alias];
  26. }
  27. throw new Error('Unknown alias: ' + alias);
  28. });
  29. var split = this.source.replace(/^\s\s*|\s\s*$/g, '').split(/\s+/);
  30. while(len--){
  31. cur = split[len] || '*';
  32. this._parseField(cur, this.map[len], this.constraints[len]);
  33. }
  34. },
  35. _parseField: function(field, type, constraints){
  36. var rangePattern = /(\d+?)(?:-(\d+?))?(?:\/(\d+?))?(?:,|$)/g,
  37. typeObj = this[type],
  38. diff,
  39. low = constraints[0],
  40. high = constraints[1];
  41. // * is a shortcut to [lower-upper] range
  42. field = field.replace(/\*/g, low + '-' + high);
  43. if(field.match(rangePattern)){
  44. field.replace(rangePattern, function($0, lower, upper, step){
  45. step = step || 1;
  46. // Positive integer higher than constraints[0]
  47. lower = Math.max(low, ~~Math.abs(lower));
  48. // Positive integer lower than constraints[1]
  49. upper = upper ? Math.min(high, ~~Math.abs(upper)) : lower;
  50. diff = step+upper-lower;
  51. while((diff -= step) > -1){
  52. typeObj[diff+lower] = true;
  53. }
  54. });
  55. }
  56. else{
  57. throw new Error('Field (' + field + ') cannot be parsed');
  58. }
  59. }
  60. };