All files / shared/utils timeComparison.ts

100% Statements 11/11
100% Branches 4/4
100% Functions 5/5
100% Lines 11/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                          683x 18430x   683x 15823x   683x 7479x         683x         37x 37x           683x       1257x  
import { isAfter, isBefore, isSameMinute, startOfMinute } from "date-fns";
 
// Comparisons date-fns has no direct equivalent for, and the two bounded-range
// checks whose exact edge behaviour matters.
//
// Compared as timestamps rather than as !isBefore / !isAfter: a negated
// comparison is true whenever either side is an invalid date, so a single
// unparseable time would turn every sign-up gate from closed to open. NaN
// compares false against everything, which keeps them closed.
 
// Program item start times are compared to the minute throughout: the same moment can be
// written two ways, since a configured time carries no milliseconds and a stored one always
// does. Invalid on either side is false, like the comparisons above.
export const isSameTime = (time: string, compared: string): boolean =>
  isSameMinute(new Date(time), new Date(compared));
 
export const isSameOrAfter = (time: Date, compared: Date): boolean =>
  time.getTime() >= compared.getTime();
 
export const isSameOrBefore = (time: Date, compared: Date): boolean =>
  time.getTime() <= compared.getTime();
 
// Whole-minute comparison including the start and excluding the end, so a
// program item starting exactly at a sign-up window's close belongs to the next
// window rather than to both
export const isWithinMinutes = (
  time: Date,
  start: Date,
  end: Date,
): boolean => {
  const minute = startOfMinute(time).getTime();
  return (
    minute >= startOfMinute(start).getTime() &&
    minute < startOfMinute(end).getTime()
  );
};
 
export const isBetweenExclusive = (
  time: Date,
  start: Date,
  end: Date,
): boolean => isAfter(time, start) && isBefore(time, end);