import toDate from '../toDate/index' ; import requiredArgs from '../_lib/requiredArgs/index' ; name category summary description param { Date | Number } dateToCompare param { Array < Date > | Array < number > } datesArray returns { Date | undefined } throws example export default function closestTo ( dirtyDateToCompare , dirtyDatesArray ) { requiredArgs ( 2 , arguments ) ; const dateToCompare = toDate ( dirtyDateToCompare ) ; if ( isNaN ( Number ( dateToCompare ) ) ) return new Date ( NaN ) ; const timeToCompare = dateToCompare . getTime ( ) ; let datesArray ; if ( dirtyDatesArray == null ) { datesArray = [ ] ; } else if ( typeof dirtyDatesArray . forEach === 'function' ) { datesArray = dirtyDatesArray ; } else { datesArray = Array . prototype . slice . call ( dirtyDatesArray ) ; } let result ; let minDistance ; datesArray . forEach ( function ( dirtyDate ) { const currentDate = toDate ( dirtyDate ) ; if ( isNaN ( Number ( currentDate ) ) ) { result = new Date ( NaN ) ; minDistance = NaN ; return ; } const distance = Math . abs ( timeToCompare - currentDate . getTime ( ) ) ; if ( result == null || distance < Number ( minDistance ) ) { result = currentDate ; minDistance = distance ; } } ) ; return result ; }