compareDesc.cjs 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. "use strict";
  2. exports.compareDesc = compareDesc;
  3. var _index = require("./toDate.cjs");
  4. /**
  5. * @name compareDesc
  6. * @category Common Helpers
  7. * @summary Compare the two dates reverse chronologically and return -1, 0 or 1.
  8. *
  9. * @description
  10. * Compare the two dates and return -1 if the first date is after the second,
  11. * 1 if the first date is before the second or 0 if dates are equal.
  12. *
  13. * @param dateLeft - The first date to compare
  14. * @param dateRight - The second date to compare
  15. *
  16. * @returns The result of the comparison
  17. *
  18. * @example
  19. * // Compare 11 February 1987 and 10 July 1989 reverse chronologically:
  20. * const result = compareDesc(new Date(1987, 1, 11), new Date(1989, 6, 10))
  21. * //=> 1
  22. *
  23. * @example
  24. * // Sort the array of dates in reverse chronological order:
  25. * const result = [
  26. * new Date(1995, 6, 2),
  27. * new Date(1987, 1, 11),
  28. * new Date(1989, 6, 10)
  29. * ].sort(compareDesc)
  30. * //=> [
  31. * // Sun Jul 02 1995 00:00:00,
  32. * // Mon Jul 10 1989 00:00:00,
  33. * // Wed Feb 11 1987 00:00:00
  34. * // ]
  35. */
  36. function compareDesc(dateLeft, dateRight) {
  37. const diff = +(0, _index.toDate)(dateLeft) - +(0, _index.toDate)(dateRight);
  38. if (diff > 0) return -1;
  39. else if (diff < 0) return 1;
  40. // Return 0 if diff is 0; return NaN if diff is NaN
  41. return diff;
  42. }