index.js 2.0 KB

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