compareAsc.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. exports.compareAsc = compareAsc;
  3. var _index = require("./toDate.js");
  4. /**
  5. * @name compareAsc
  6. * @category Common Helpers
  7. * @summary Compare the two dates 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. * @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).
  14. *
  15. * @param dateLeft - The first date to compare
  16. * @param dateRight - The second date to compare
  17. *
  18. * @returns The result of the comparison
  19. *
  20. * @example
  21. * // Compare 11 February 1987 and 10 July 1989:
  22. * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))
  23. * //=> -1
  24. *
  25. * @example
  26. * // Sort the array of dates:
  27. * const result = [
  28. * new Date(1995, 6, 2),
  29. * new Date(1987, 1, 11),
  30. * new Date(1989, 6, 10)
  31. * ].sort(compareAsc)
  32. * //=> [
  33. * // Wed Feb 11 1987 00:00:00,
  34. * // Mon Jul 10 1989 00:00:00,
  35. * // Sun Jul 02 1995 00:00:00
  36. * // ]
  37. */
  38. function compareAsc(dateLeft, dateRight) {
  39. const _dateLeft = (0, _index.toDate)(dateLeft);
  40. const _dateRight = (0, _index.toDate)(dateRight);
  41. const diff = _dateLeft.getTime() - _dateRight.getTime();
  42. if (diff < 0) {
  43. return -1;
  44. } else if (diff > 0) {
  45. return 1;
  46. // Return 0 if diff is 0; return NaN if diff is NaN
  47. } else {
  48. return diff;
  49. }
  50. }