Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 

65 rader
2.0 KiB

  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 Return the earliest of the given dates.
  7. *
  8. * @description
  9. * Return 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. * var date1 = new Date(1989, 6, 10)
  20. * var date2 = new Date(1987, 1, 11)
  21. * var minDate = min(date1, date2)
  22. *
  23. * // v2.0.0 onward:
  24. * var dates = [new Date(1989, 6, 10), new Date(1987, 1, 11)]
  25. * var 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. * var 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)) {
  57. result = currentDate;
  58. }
  59. });
  60. return result || new Date(NaN);
  61. }