compareAsc.mjs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { toDate } from "./toDate.mjs";
  2. /**
  3. * @name compareAsc
  4. * @category Common Helpers
  5. * @summary Compare the two dates 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. * @typeParam DateType - The `Date` type, the function operates on. Gets inferred from passed arguments. Allows to use extensions like [`UTCDate`](https://github.com/date-fns/utc).
  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:
  20. * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))
  21. * //=> -1
  22. *
  23. * @example
  24. * // Sort the array of dates:
  25. * const result = [
  26. * new Date(1995, 6, 2),
  27. * new Date(1987, 1, 11),
  28. * new Date(1989, 6, 10)
  29. * ].sort(compareAsc)
  30. * //=> [
  31. * // Wed Feb 11 1987 00:00:00,
  32. * // Mon Jul 10 1989 00:00:00,
  33. * // Sun Jul 02 1995 00:00:00
  34. * // ]
  35. */
  36. export function compareAsc(dateLeft, dateRight) {
  37. const _dateLeft = toDate(dateLeft);
  38. const _dateRight = toDate(dateRight);
  39. const diff = _dateLeft.getTime() - _dateRight.getTime();
  40. if (diff < 0) {
  41. return -1;
  42. } else if (diff > 0) {
  43. return 1;
  44. // Return 0 if diff is 0; return NaN if diff is NaN
  45. } else {
  46. return diff;
  47. }
  48. }
  49. // Fallback for modularized imports:
  50. export default compareAsc;