index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = max;
  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 max
  11. * @category Common Helpers
  12. * @summary Return the latest of the given dates.
  13. *
  14. * @description
  15. * Return the latest of the given dates.
  16. *
  17. * ### v2.0.0 breaking changes:
  18. *
  19. * - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
  20. *
  21. * - `max` function now accepts an array of dates rather than spread arguments.
  22. *
  23. * ```javascript
  24. * // Before v2.0.0
  25. * var date1 = new Date(1989, 6, 10)
  26. * var date2 = new Date(1987, 1, 11)
  27. * var maxDate = max(date1, date2)
  28. *
  29. * // v2.0.0 onward:
  30. * var dates = [new Date(1989, 6, 10), new Date(1987, 1, 11)]
  31. * var maxDate = max(dates)
  32. * ```
  33. *
  34. * @param {Date[]|Number[]} datesArray - the dates to compare
  35. * @returns {Date} the latest of the dates
  36. * @throws {TypeError} 1 argument required
  37. *
  38. * @example
  39. * // Which of these dates is the latest?
  40. * var result = max([
  41. * new Date(1989, 6, 10),
  42. * new Date(1987, 1, 11),
  43. * new Date(1995, 6, 2),
  44. * new Date(1990, 0, 1)
  45. * ])
  46. * //=> Sun Jul 02 1995 00:00:00
  47. */
  48. function max(dirtyDatesArray) {
  49. (0, _index2.default)(1, arguments);
  50. var datesArray; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method
  51. if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') {
  52. datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array.
  53. } else if (typeof dirtyDatesArray === 'object' && dirtyDatesArray !== null) {
  54. datesArray = Array.prototype.slice.call(dirtyDatesArray);
  55. } else {
  56. // `dirtyDatesArray` is non-iterable, return Invalid Date
  57. return new Date(NaN);
  58. }
  59. var result;
  60. datesArray.forEach(function (dirtyDate) {
  61. var currentDate = (0, _index.default)(dirtyDate);
  62. if (result === undefined || result < currentDate || isNaN(Number(currentDate))) {
  63. result = currentDate;
  64. }
  65. });
  66. return result || new Date(NaN);
  67. }
  68. module.exports = exports.default;