index.js
2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = closestIndexTo;
var _index = _interopRequireDefault(require("../toDate/index.js"));
var _index2 = _interopRequireDefault(require("../_lib/requiredArgs/index.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* @name closestIndexTo
* @category Common Helpers
* @summary Return an index of the closest date from the array comparing to the given date.
*
* @description
* Return an index of the closest date from the array comparing to the given date.
*
* ### v2.0.0 breaking changes:
*
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes).
*
* - Now, `closestIndexTo` doesn't throw an exception
* when the second argument is not an array, and returns Invalid Date instead.
*
* @param {Date|Number} dateToCompare - the date to compare with
* @param {Date[]|Number[]} datesArray - the array to search
* @returns {Number} an index of the date closest to the given date
* @throws {TypeError} 2 arguments required
*
* @example
* // Which date is closer to 6 September 2015?
* var dateToCompare = new Date(2015, 8, 6)
* var datesArray = [
* new Date(2015, 0, 1),
* new Date(2016, 0, 1),
* new Date(2017, 0, 1)
* ]
* var result = closestIndexTo(dateToCompare, datesArray)
* //=> 1
*/
function closestIndexTo(dirtyDateToCompare, dirtyDatesArray) {
(0, _index2.default)(2, arguments);
var dateToCompare = (0, _index.default)(dirtyDateToCompare);
if (isNaN(dateToCompare)) {
return NaN;
}
var timeToCompare = dateToCompare.getTime();
var datesArray; // `dirtyDatesArray` is undefined or null
if (dirtyDatesArray == null) {
datesArray = []; // `dirtyDatesArray` is Array, Set or Map, or object with custom `forEach` method
} else if (typeof dirtyDatesArray.forEach === 'function') {
datesArray = dirtyDatesArray; // If `dirtyDatesArray` is Array-like Object, convert to Array. Otherwise, make it empty Array
} else {
datesArray = Array.prototype.slice.call(dirtyDatesArray);
}
var result;
var minDistance;
datesArray.forEach(function (dirtyDate, index) {
var currentDate = (0, _index.default)(dirtyDate);
if (isNaN(currentDate)) {
result = NaN;
minDistance = NaN;
return;
}
var distance = Math.abs(timeToCompare - currentDate.getTime());
if (result == null || distance < minDistance) {
result = index;
minDistance = distance;
}
});
return result;
}
module.exports = exports.default;