-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
index.js
44 lines (40 loc) · 1.4 KB
/
index.js
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
import toDate from '../toDate/index.js'
/**
* @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.
*
* @param {Date|String|Number} dateToCompare - the date to compare with
* @param {Date[]|String[]|Number[]} datesArray - the array to search
* @param {Options} [options] - the object with options. See [Options]{@link docs/Options}
* @returns {Number} an index of the date closest to the given date
*
* @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
*/
export default function closestIndexTo (dirtyDateToCompare, dirtyDatesArray, dirtyOptions) {
var dateToCompare = toDate(dirtyDateToCompare, dirtyOptions)
var timeToCompare = dateToCompare.getTime()
var result
var minDistance
dirtyDatesArray.forEach(function (dirtyDate, index) {
var currentDate = toDate(dirtyDate, dirtyOptions)
var distance = Math.abs(timeToCompare - currentDate.getTime())
if (result === undefined || distance < minDistance) {
result = index
minDistance = distance
}
})
return result
}