index.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import toDate from "../toDate/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. /**
  4. * @name min
  5. * @category Common Helpers
  6. * @summary Returns the earliest of the given dates.
  7. *
  8. * @description
  9. * Returns the earliest 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. * - `min` function now accepts an array of dates rather than spread arguments.
  16. *
  17. * ```javascript
  18. * // Before v2.0.0
  19. * const date1 = new Date(1989, 6, 10)
  20. * const date2 = new Date(1987, 1, 11)
  21. * const minDate = min(date1, date2)
  22. *
  23. * // v2.0.0 onward:
  24. * const dates = [new Date(1989, 6, 10), new Date(1987, 1, 11)]
  25. * const minDate = min(dates)
  26. * ```
  27. *
  28. * @param {Date[]|Number[]} datesArray - the dates to compare
  29. * @returns {Date} - the earliest of the dates
  30. * @throws {TypeError} 1 argument required
  31. *
  32. * @example
  33. * // Which of these dates is the earliest?
  34. * const result = min([
  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. * //=> Wed Feb 11 1987 00:00:00
  41. */
  42. export default function min(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(currentDate.getDate())) {
  57. result = currentDate;
  58. }
  59. });
  60. return result || new Date(NaN);
  61. }