index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. var parse = require('../parse/index.js')
  2. /**
  3. * @category Range Helpers
  4. * @summary Is the given date range overlapping with another date range?
  5. *
  6. * @description
  7. * Is the given date range overlapping with another date range?
  8. *
  9. * @param {Date|String|Number} initialRangeStartDate - the start of the initial range
  10. * @param {Date|String|Number} initialRangeEndDate - the end of the initial range
  11. * @param {Date|String|Number} comparedRangeStartDate - the start of the range to compare it with
  12. * @param {Date|String|Number} comparedRangeEndDate - the end of the range to compare it with
  13. * @returns {Boolean} whether the date ranges are overlapping
  14. * @throws {Error} startDate of a date range cannot be after its endDate
  15. *
  16. * @example
  17. * // For overlapping date ranges:
  18. * areRangesOverlapping(
  19. * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 17), new Date(2014, 0, 21)
  20. * )
  21. * //=> true
  22. *
  23. * @example
  24. * // For non-overlapping date ranges:
  25. * areRangesOverlapping(
  26. * new Date(2014, 0, 10), new Date(2014, 0, 20), new Date(2014, 0, 21), new Date(2014, 0, 22)
  27. * )
  28. * //=> false
  29. */
  30. function areRangesOverlapping (dirtyInitialRangeStartDate, dirtyInitialRangeEndDate, dirtyComparedRangeStartDate, dirtyComparedRangeEndDate) {
  31. var initialStartTime = parse(dirtyInitialRangeStartDate).getTime()
  32. var initialEndTime = parse(dirtyInitialRangeEndDate).getTime()
  33. var comparedStartTime = parse(dirtyComparedRangeStartDate).getTime()
  34. var comparedEndTime = parse(dirtyComparedRangeEndDate).getTime()
  35. if (initialStartTime > initialEndTime || comparedStartTime > comparedEndTime) {
  36. throw new Error('The start of the range cannot be after the end of the range')
  37. }
  38. return initialStartTime < comparedEndTime && comparedStartTime < initialEndTime
  39. }
  40. module.exports = areRangesOverlapping