index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import toDate from "../toDate/index.js";
  2. import requiredArgs from "../_lib/requiredArgs/index.js";
  3. /**
  4. * @name closestIndexTo
  5. * @category Common Helpers
  6. * @summary Return an index of the closest date from the array comparing to the given date.
  7. *
  8. * @description
  9. * Return an index of the closest date from the array comparing to the given date.
  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. * - Now, `closestIndexTo` doesn't throw an exception
  16. * when the second argument is not an array, and returns Invalid Date instead.
  17. *
  18. * @param {Date|Number} dateToCompare - the date to compare with
  19. * @param {Date[]|Number[]} datesArray - the array to search
  20. * @returns {Number} an index of the date closest to the given date
  21. * @throws {TypeError} 2 arguments required
  22. *
  23. * @example
  24. * // Which date is closer to 6 September 2015?
  25. * var dateToCompare = new Date(2015, 8, 6)
  26. * var datesArray = [
  27. * new Date(2015, 0, 1),
  28. * new Date(2016, 0, 1),
  29. * new Date(2017, 0, 1)
  30. * ]
  31. * var result = closestIndexTo(dateToCompare, datesArray)
  32. * //=> 1
  33. */
  34. export default function closestIndexTo(dirtyDateToCompare, dirtyDatesArray) {
  35. requiredArgs(2, arguments);
  36. var dateToCompare = toDate(dirtyDateToCompare);
  37. if (isNaN(dateToCompare)) {
  38. return NaN;
  39. }
  40. var timeToCompare = dateToCompare.getTime();
  41. var datesArray; // `dirtyDatesArray` is undefined or null
  42. if (dirtyDatesArray == null) {
  43. datesArray = []; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method
  44. } else if (typeof dirtyDatesArray.forEach === 'function') {
  45. datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. Otherwise, make it empty Array
  46. } else {
  47. datesArray = Array.prototype.slice.call(dirtyDatesArray);
  48. }
  49. var result;
  50. var minDistance;
  51. datesArray.forEach(function (dirtyDate, index) {
  52. var currentDate = toDate(dirtyDate);
  53. if (isNaN(currentDate)) {
  54. result = NaN;
  55. minDistance = NaN;
  56. return;
  57. }
  58. var distance = Math.abs(timeToCompare - currentDate.getTime());
  59. if (result == null || distance < minDistance) {
  60. result = index;
  61. minDistance = distance;
  62. }
  63. });
  64. return result;
  65. }