index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import _typeof from "@babel/runtime/helpers/esm/typeof";
  2. import toDate from "../toDate/index.js";
  3. import requiredArgs from "../_lib/requiredArgs/index.js";
  4. /**
  5. * @name max
  6. * @category Common Helpers
  7. * @summary Return the latest of the given dates.
  8. *
  9. * @description
  10. * Return the latest of the given dates.
  11. *
  12. * @param {Date[]|Number[]} datesArray - the dates to compare
  13. * @returns {Date} the latest of the dates
  14. * @throws {TypeError} 1 argument required
  15. *
  16. * @example
  17. * // Which of these dates is the latest?
  18. * const result = max([
  19. * new Date(1989, 6, 10),
  20. * new Date(1987, 1, 11),
  21. * new Date(1995, 6, 2),
  22. * new Date(1990, 0, 1)
  23. * ])
  24. * //=> Sun Jul 02 1995 00:00:00
  25. */
  26. export default function max(dirtyDatesArray) {
  27. requiredArgs(1, arguments);
  28. var datesArray;
  29. // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method
  30. if (dirtyDatesArray && typeof dirtyDatesArray.forEach === 'function') {
  31. datesArray = dirtyDatesArray;
  32. // If `dirtyDatesArray` is Array-like Object, convert to Array.
  33. } else if (_typeof(dirtyDatesArray) === 'object' && dirtyDatesArray !== null) {
  34. datesArray = Array.prototype.slice.call(dirtyDatesArray);
  35. } else {
  36. // `dirtyDatesArray` is non-iterable, return Invalid Date
  37. return new Date(NaN);
  38. }
  39. var result;
  40. datesArray.forEach(function (dirtyDate) {
  41. var currentDate = toDate(dirtyDate);
  42. if (result === undefined || result < currentDate || isNaN(Number(currentDate))) {
  43. result = currentDate;
  44. }
  45. });
  46. return result || new Date(NaN);
  47. }