index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = compareDesc;
  6. var _index = _interopRequireDefault(require("../toDate/index.js"));
  7. var _index2 = _interopRequireDefault(require("../_lib/requiredArgs/index.js"));
  8. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  9. /**
  10. * @name compareDesc
  11. * @category Common Helpers
  12. * @summary Compare the two dates reverse chronologically and return -1, 0 or 1.
  13. *
  14. * @description
  15. * Compare the two dates and return -1 if the first date is after the second,
  16. * 1 if the first date is before the second or 0 if dates are equal.
  17. *
  18. * ### v2.0.0 breaking changes:
  19. *
  20. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  21. *
  22. * @param {Date|Number} dateLeft - the first date to compare
  23. * @param {Date|Number} dateRight - the second date to compare
  24. * @returns {Number} the result of the comparison
  25. * @throws {TypeError} 2 arguments required
  26. *
  27. * @example
  28. * // Compare 11 February 1987 and 10 July 1989 reverse chronologically:
  29. * const result = compareDesc(new Date(1987, 1, 11), new Date(1989, 6, 10))
  30. * //=> 1
  31. *
  32. * @example
  33. * // Sort the array of dates in reverse chronological order:
  34. * const result = [
  35. * new Date(1995, 6, 2),
  36. * new Date(1987, 1, 11),
  37. * new Date(1989, 6, 10)
  38. * ].sort(compareDesc)
  39. * //=> [
  40. * // Sun Jul 02 1995 00:00:00,
  41. * // Mon Jul 10 1989 00:00:00,
  42. * // Wed Feb 11 1987 00:00:00
  43. * // ]
  44. */
  45. function compareDesc(dirtyDateLeft, dirtyDateRight) {
  46. (0, _index2.default)(2, arguments);
  47. var dateLeft = (0, _index.default)(dirtyDateLeft);
  48. var dateRight = (0, _index.default)(dirtyDateRight);
  49. var diff = dateLeft.getTime() - dateRight.getTime();
  50. if (diff > 0) {
  51. return -1;
  52. } else if (diff < 0) {
  53. return 1; // Return 0 if diff is 0; return NaN if diff is NaN
  54. } else {
  55. return diff;
  56. }
  57. }
  58. module.exports = exports.default;