index.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.default = closestTo;
  7. var _index = _interopRequireDefault(require("../toDate/index.js"));
  8. var _index2 = _interopRequireDefault(require("../_lib/requiredArgs/index.js"));
  9. /**
  10. * @name closestTo
  11. * @category Common Helpers
  12. * @summary Return a date from the array closest to the given date.
  13. *
  14. * @description
  15. * Return a date from the array closest to the given date.
  16. *
  17. * @param {Date | Number} dateToCompare - the date to compare with
  18. * @param {Array<Date> | Array<number>} datesArray - the array to search
  19. * @returns {Date | undefined} the date from the array closest to the given date or undefined if no valid value is given
  20. * @throws {TypeError} 2 arguments required
  21. *
  22. * @example
  23. * // Which date is closer to 6 September 2015: 1 January 2000 or 1 January 2030?
  24. * const dateToCompare = new Date(2015, 8, 6)
  25. * const result = closestTo(dateToCompare, [
  26. * new Date(2000, 0, 1),
  27. * new Date(2030, 0, 1)
  28. * ])
  29. * //=> Tue Jan 01 2030 00:00:00
  30. */
  31. function closestTo(dirtyDateToCompare, dirtyDatesArray) {
  32. (0, _index2.default)(2, arguments);
  33. var dateToCompare = (0, _index.default)(dirtyDateToCompare);
  34. if (isNaN(Number(dateToCompare))) return new Date(NaN);
  35. var timeToCompare = dateToCompare.getTime();
  36. var datesArray;
  37. // `dirtyDatesArray` is undefined or null
  38. if (dirtyDatesArray == null) {
  39. datesArray = [];
  40. // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method
  41. } else if (typeof dirtyDatesArray.forEach === 'function') {
  42. datesArray = dirtyDatesArray;
  43. // If `dirtyDatesArray` is Array-like Object, convert to Array. Otherwise, make it empty Array
  44. } else {
  45. datesArray = Array.prototype.slice.call(dirtyDatesArray);
  46. }
  47. var result;
  48. var minDistance;
  49. datesArray.forEach(function (dirtyDate) {
  50. var currentDate = (0, _index.default)(dirtyDate);
  51. if (isNaN(Number(currentDate))) {
  52. result = new Date(NaN);
  53. minDistance = NaN;
  54. return;
  55. }
  56. var distance = Math.abs(timeToCompare - currentDate.getTime());
  57. if (result == null || distance < Number(minDistance)) {
  58. result = currentDate;
  59. minDistance = distance;
  60. }
  61. });
  62. return result;
  63. }
  64. module.exports = exports.default;