Brute force and assuming no particular order to dates
is the obvious solution. Runs in linear time. Something like this:
function findNextDate( now = Date.now() ) {
let next = undefined;
for ( const dt of dates ) {
next = next === undefined
? next
: dt < next
? dt
: next
;
}
return next;
}
But if one can assume an ordered collection, use a modified binary search like this:
const dates = [ ... ];
function findNextDate( now = Date.now() ) {
if ( dates.length === 0 ) return undefined;
let lo = 0 ;
let hi = dates.length;
while ( lo != hi ) {
let mid = Math.floor( (lo+hi) / 2 );
if ( dates[mid] > now ) {
hi = mid;
} else {
lo = mid+1;
}
}
const next = dates[lo];
return next;
}
which will return the smallest item in the ordered array such that it is greater than the target value. Credits to this answer to the question, Find the first element in a sorted array that is greater than the target
A more open-ended solution is a little date arithmetic instead of an array:
function getSundayNext( dtNow = new Date() ) {
const dow = dtNow.getDay();
const daysUntilSunday = 7 - dow;
const nextSunday = new Date( dtNow.valueOf() );
nextSunday.setDate( dtNow.getDate() + daysUntilSunday );
nextSunday.setHours(0);
nextSunday.setMinutes(0);
nextSunday.setSeconds(0);
nextSunday.setMilliseconds(0);
return nextSunday;
}