index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. var parse = require('../parse/index.js')
  2. /**
  3. * @category Common Helpers
  4. * @summary Return a date from the array closest to the given date.
  5. *
  6. * @description
  7. * Return a date from the array closest 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 {Date} the date from the array 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: 1 January 2000 or 1 January 2030?
  16. * var dateToCompare = new Date(2015, 8, 6)
  17. * var result = closestTo(dateToCompare, [
  18. * new Date(2000, 0, 1),
  19. * new Date(2030, 0, 1)
  20. * ])
  21. * //=> Tue Jan 01 2030 00:00:00
  22. */
  23. function closestTo (dirtyDateToCompare, dirtyDatesArray) {
  24. if (!(dirtyDatesArray instanceof Array)) {
  25. throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array')
  26. }
  27. var dateToCompare = parse(dirtyDateToCompare)
  28. var timeToCompare = dateToCompare.getTime()
  29. var result
  30. var minDistance
  31. dirtyDatesArray.forEach(function (dirtyDate) {
  32. var currentDate = parse(dirtyDate)
  33. var distance = Math.abs(timeToCompare - currentDate.getTime())
  34. if (result === undefined || distance < minDistance) {
  35. result = currentDate
  36. minDistance = distance
  37. }
  38. })
  39. return result
  40. }
  41. module.exports = closestTo