UNPKG

nearest-date

Version:

Given an array of dates, this module will find the date nearest to a given target date. Can be used to find the nearest number as well

21 lines (16 loc) 441 B
'use strict' module.exports = function (dates, target) { if (!target) target = Date.now() else if (target instanceof Date) target = target.getTime() var nearest = Infinity var winner = -1 dates.forEach(function (date, index) { if (date instanceof Date) date = date.getTime() var distance = Math.abs(date - target) if (distance < nearest) { nearest = distance winner = index } }) return winner }