index.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.default = compareDesc;
  7. var _index = _interopRequireDefault(require("../toDate/index.js"));
  8. var _index2 = _interopRequireDefault(require("../_lib/requiredArgs/index.js"));
  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. * @param {Date|Number} dateLeft - the first date to compare
  19. * @param {Date|Number} dateRight - the second date to compare
  20. * @returns {Number} the result of the comparison
  21. * @throws {TypeError} 2 arguments required
  22. *
  23. * @example
  24. * // Compare 11 February 1987 and 10 July 1989 reverse chronologically:
  25. * const result = compareDesc(new Date(1987, 1, 11), new Date(1989, 6, 10))
  26. * //=> 1
  27. *
  28. * @example
  29. * // Sort the array of dates in reverse chronological order:
  30. * const result = [
  31. * new Date(1995, 6, 2),
  32. * new Date(1987, 1, 11),
  33. * new Date(1989, 6, 10)
  34. * ].sort(compareDesc)
  35. * //=> [
  36. * // Sun Jul 02 1995 00:00:00,
  37. * // Mon Jul 10 1989 00:00:00,
  38. * // Wed Feb 11 1987 00:00:00
  39. * // ]
  40. */
  41. function compareDesc(dirtyDateLeft, dirtyDateRight) {
  42. (0, _index2.default)(2, arguments);
  43. var dateLeft = (0, _index.default)(dirtyDateLeft);
  44. var dateRight = (0, _index.default)(dirtyDateRight);
  45. var diff = dateLeft.getTime() - dateRight.getTime();
  46. if (diff > 0) {
  47. return -1;
  48. } else if (diff < 0) {
  49. return 1;
  50. // Return 0 if diff is 0; return NaN if diff is NaN
  51. } else {
  52. return diff;
  53. }
  54. }
  55. module.exports = exports.default;