index.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. * @param {Date | Number} dateToCompare - the date to compare with
  12. * @param {Array<Date> | Array<number>} datesArray - the array to search
  13. * @returns {Number | undefined} an index of the date closest to the given date or undefined if no valid value is given
  14. * @throws {TypeError} 2 arguments required
  15. *
  16. * @example
  17. * // Which date is closer to 6 September 2015?
  18. * const dateToCompare = new Date(2015, 8, 6)
  19. * const datesArray = [
  20. * new Date(2015, 0, 1),
  21. * new Date(2016, 0, 1),
  22. * new Date(2017, 0, 1)
  23. * ]
  24. * const result = closestIndexTo(dateToCompare, datesArray)
  25. * //=> 1
  26. */
  27. export default function closestIndexTo(dirtyDateToCompare, dirtyDatesArray) {
  28. requiredArgs(2, arguments);
  29. var dateToCompare = toDate(dirtyDateToCompare);
  30. if (isNaN(Number(dateToCompare))) return NaN;
  31. var timeToCompare = dateToCompare.getTime();
  32. var datesArray;
  33. // `dirtyDatesArray` is undefined or null
  34. if (dirtyDatesArray == null) {
  35. datesArray = [];
  36. // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method
  37. } else if (typeof dirtyDatesArray.forEach === 'function') {
  38. datesArray = dirtyDatesArray;
  39. // If `dirtyDatesArray` is Array-like Object, convert to Array. Otherwise, make it empty Array
  40. } else {
  41. datesArray = Array.prototype.slice.call(dirtyDatesArray);
  42. }
  43. var result;
  44. var minDistance;
  45. datesArray.forEach(function (dirtyDate, index) {
  46. var currentDate = toDate(dirtyDate);
  47. if (isNaN(Number(currentDate))) {
  48. result = NaN;
  49. minDistance = NaN;
  50. return;
  51. }
  52. var distance = Math.abs(timeToCompare - currentDate.getTime());
  53. if (result == null || distance < Number(minDistance)) {
  54. result = index;
  55. minDistance = distance;
  56. }
  57. });
  58. return result;
  59. }