compareDesc.js 1.3 KB

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