index.js
1.47 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
var parse = require('../parse/index.js')
/**
* @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
* @returns {Number} an index of the date closest to the given date
* @throws {TypeError} the second argument must be an instance of Array
*
* @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) {
if (!(dirtyDatesArray instanceof Array)) {
throw new TypeError(toString.call(dirtyDatesArray) + ' is not an instance of Array')
}
var dateToCompare = parse(dirtyDateToCompare)
var timeToCompare = dateToCompare.getTime()
var result
var minDistance
dirtyDatesArray.forEach(function (dirtyDate, index) {
var currentDate = parse(dirtyDate)
var distance = Math.abs(timeToCompare - currentDate.getTime())
if (result === undefined || distance < minDistance) {
result = index
minDistance = distance
}
})
return result
}
module.exports = closestIndexTo