All files / presentation/ui/src timeUtils.ts

100% Statements 21/21
100% Branches 20/20
100% Functions 6/6
100% Lines 21/21

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 44 45 46 47 48 49 50 51 52 53 54 55 56 57        1039x       6x 6x           13x 5x   8x 8x   8x       164x 164x 12x   152x 96x     56x           301x 22x   279x 279x             145x 145x     145x    
import { round } from "lodash";
import { formatDisplayTime } from "./TimeDisplay";
 
export function isValidTimestamp(time: number): boolean {
  return Number.isFinite(time) && time > 0;
}
 
export function getFormattedTime(arrival: number): string {
  const formatted = formatDisplayTime(arrival, "12h", "default");
  return isValidTimestamp(arrival)
    ? formatted.replace(/\s/g, "").toLowerCase()
    : formatted;
}
 
export function getFormattedLoadTime(time: number): string {
  if (!isValidTimestamp(time)) {
    return "Time unavailable";
  }
  const weekday = new Intl.DateTimeFormat("en-US", { weekday: "short" }).format(time);
  const clock = formatDisplayTime(time, "12h", "default", undefined, true)
    .replace(/\s+/g, " ").toLowerCase();
  return `${weekday}, ${clock}`;
}
 
export function getNormalizedTimeDifference(time: number, toTime: number): string {
  const minutesUntilArrival = getTimeDifferenceInMinutes(time, toTime);
  if (minutesUntilArrival === null) {
    return "Time unavailable";
  }
  if (time <= toTime) {
    return "Due";
  }
 
  return minutesUntilArrival >= 60
    ? `${round((time - toTime) / 3600000, 1)} hrs`
    : `${minutesUntilArrival} min`;
}
 
export function getTimeDifferenceInMinutes(time: number, toTime: number): number | null {
  if (!isValidTimestamp(time) || !isValidTimestamp(toTime)) {
    return null;
  }
  const minutes = Math.trunc((time - toTime) / 60000);
  return minutes === 0 ? 0 : minutes;
}
 
export function getTimeUntilArrival(
  estimatedArrivalTime: number,
  scheduledArrivalTime: number
): string {
  const now = Date.now();
  const timeStampToDiff = isValidTimestamp(estimatedArrivalTime)
    ? estimatedArrivalTime
    : scheduledArrivalTime;
  return getNormalizedTimeDifference(timeStampToDiff, now);
}