index.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. var parse = require('../parse/index.js')
  2. /**
  3. * @category Common Helpers
  4. * @summary Return an index of the closest date from the array comparing to the given date.
  5. *
  6. * @description
  7. * Return an index of the closest date from the array comparing to the given date.
  8. *
  9. * @param {Date|String|Number} dateToCompare - the date to compare with
  10. * @param {Date[]|String[]|Number[]} datesArray - the array to search
  11. * @returns {Number} an index of the date closest to the given date
  12. * @throws {TypeError} the second argument must be an instance of Array
  13. *
  14. * @example
  15. * // Which date is closer to 6 September 2015?
  16. * var dateToCompare = new Date(2015, 8, 6)
  17. * var datesArray = [
  18. * new Date(2015, 0, 1),
  19. * new Date(2016, 0, 1),
  20. * new Date(2017, 0, 1)
  21. * ]
  22. * var result = closestIndexTo(dateToCompare, datesArray)
  23. * //=> 1
  24. */
  25. function closestIndexTo (dirtyDateToCompare, dirtyDatesArray) {
  26. if (!(dirtyDatesArray instanceof Array)) {
  27. throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array')
  28. }
  29. var dateToCompare = parse(dirtyDateToCompare)
  30. var timeToCompare = dateToCompare.getTime()
  31. var result
  32. var minDistance
  33. dirtyDatesArray.forEach(function (dirtyDate, index) {
  34. var currentDate = parse(dirtyDate)
  35. var distance = Math.abs(timeToCompare - currentDate.getTime())
  36. if (result === undefined || distance < minDistance) {
  37. result = index
  38. minDistance = distance
  39. }
  40. })
  41. return result
  42. }
  43. module.exports = closestIndexTo