index.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import toDate from "../toDate/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. /**
  4. * @name compareDesc
  5. * @category Common Helpers
  6. * @summary Compare the two dates reverse chronologically and return -1, 0 or 1.
  7. *
  8. * @description
  9. * Compare the two dates and return -1 if the first date is after the second,
  10. * 1 if the first date is before the second or 0 if dates are equal.
  11. *
  12. * ### v2.0.0 breaking changes:
  13. *
  14. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  15. *
  16. * @param {Date|Number} dateLeft - the first date to compare
  17. * @param {Date|Number} dateRight - the second date to compare
  18. * @returns {Number} the result of the comparison
  19. * @throws {TypeError} 2 arguments required
  20. *
  21. * @example
  22. * // Compare 11 February 1987 and 10 July 1989 reverse chronologically:
  23. * const result = compareDesc(new Date(1987, 1, 11), new Date(1989, 6, 10))
  24. * //=> 1
  25. *
  26. * @example
  27. * // Sort the array of dates in reverse chronological order:
  28. * const result = [
  29. * new Date(1995, 6, 2),
  30. * new Date(1987, 1, 11),
  31. * new Date(1989, 6, 10)
  32. * ].sort(compareDesc)
  33. * //=> [
  34. * // Sun Jul 02 1995 00:00:00,
  35. * // Mon Jul 10 1989 00:00:00,
  36. * // Wed Feb 11 1987 00:00:00
  37. * // ]
  38. */
  39. export default function compareDesc(dirtyDateLeft, dirtyDateRight) {
  40. requiredArgs(2, arguments);
  41. var dateLeft = toDate(dirtyDateLeft);
  42. var dateRight = toDate(dirtyDateRight);
  43. var diff = dateLeft.getTime() - dateRight.getTime();
  44. if (diff > 0) {
  45. return -1;
  46. } else if (diff < 0) {
  47. return 1; // Return 0 if diff is 0; return NaN if diff is NaN
  48. } else {
  49. return diff;
  50. }
  51. }