You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

weekdayRange.js 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * Module exports.
  3. */
  4. module.exports = weekdayRange;
  5. /**
  6. * Only the first parameter is mandatory. Either the second, the third, or both
  7. * may be left out.
  8. *
  9. * If only one parameter is present, the function yeilds a true value on the
  10. * weekday that the parameter represents. If the string "GMT" is specified as
  11. * a second parameter, times are taken to be in GMT, otherwise in local timezone.
  12. *
  13. * If both wd1 and wd1 are defined, the condition is true if the current weekday
  14. * is in between those two weekdays. Bounds are inclusive. If the "GMT" parameter
  15. * is specified, times are taken to be in GMT, otherwise the local timezone is
  16. * used.
  17. *
  18. * Valid "weekday strings" are:
  19. *
  20. * SUN MON TUE WED THU FRI SAT
  21. *
  22. * Examples:
  23. *
  24. * ``` js
  25. * weekdayRange("MON", "FRI")
  26. * true Monday trhough Friday (local timezone).
  27. *
  28. * weekdayRange("MON", "FRI", "GMT")
  29. * same as above, but GMT timezone.
  30. *
  31. * weekdayRange("SAT")
  32. * true on Saturdays local time.
  33. *
  34. * weekdayRange("SAT", "GMT")
  35. * true on Saturdays GMT time.
  36. *
  37. * weekdayRange("FRI", "MON")
  38. * true Friday through Monday (note, order does matter!).
  39. * ```
  40. *
  41. *
  42. * @param {String} wd1 one of the weekday strings.
  43. * @param {String} wd2 one of the weekday strings.
  44. * @param {String} gmt is either the string: GMT or is left out.
  45. * @return {Boolean}
  46. */
  47. const dayOrder = { "SUN": 0, "MON": 1, "TUE": 2, "WED": 3, "THU": 4, "FRI": 5, "SAT": 6 };
  48. function weekdayRange (wd1, wd2, gmt) {
  49. var useGMTzone = (wd2 == "GMT" || gmt == "GMT"),
  50. todaysDay = getTodaysDay(useGMTzone),
  51. wd1Index = dayOrder[wd1] || -1,
  52. wd2Index = dayOrder[wd2] || -1,
  53. result = false;
  54. if (wd2Index < 0) {
  55. result = (todaysDay == wd1Index);
  56. } else {
  57. if (wd1Index <= wd2Index) {
  58. result = valueInRange(wd1Index, todaysDay, wd2Index);
  59. } else {
  60. result = valueInRange(wd1Index, todaysDay, 6) || valueInRange(0, todaysDay, wd2Index);
  61. }
  62. }
  63. return result;
  64. }
  65. function getTodaysDay (gmt) {
  66. return (gmt ? (new Date()).getUTCDay() : (new Date()).getDay());
  67. }
  68. // start <= value <= finish
  69. function valueInRange (start, value, finish) {
  70. return (start <= value) && (value <= finish);
  71. }