index.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import toDate from "../toDate/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. /**
  4. * @name compareAsc
  5. * @category Common Helpers
  6. * @summary Compare the two dates 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. * @param {Date|Number} dateLeft - the first date to compare
  13. * @param {Date|Number} dateRight - the second date to compare
  14. * @returns {Number} the result of the comparison
  15. * @throws {TypeError} 2 arguments required
  16. *
  17. * @example
  18. * // Compare 11 February 1987 and 10 July 1989:
  19. * const result = compareAsc(new Date(1987, 1, 11), new Date(1989, 6, 10))
  20. * //=> -1
  21. *
  22. * @example
  23. * // Sort the array of dates:
  24. * const result = [
  25. * new Date(1995, 6, 2),
  26. * new Date(1987, 1, 11),
  27. * new Date(1989, 6, 10)
  28. * ].sort(compareAsc)
  29. * //=> [
  30. * // Wed Feb 11 1987 00:00:00,
  31. * // Mon Jul 10 1989 00:00:00,
  32. * // Sun Jul 02 1995 00:00:00
  33. * // ]
  34. */
  35. export default function compareAsc(dirtyDateLeft, dirtyDateRight) {
  36. requiredArgs(2, arguments);
  37. var dateLeft = toDate(dirtyDateLeft);
  38. var dateRight = toDate(dirtyDateRight);
  39. var 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. }