All files TimeIntervalUtils.ts

75.47% Statements 40/53
80% Branches 4/5
100% Functions 3/3
75.47% Lines 40/53

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 541x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x                           1x 1x 16x 16x 16x 16x 16x 16x 16x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x  
import { DateTime } from "luxon"
 
import { TimeInterval } from "../types/settings"
 
const TIME_ZONE = "America/Los_Angeles"
 
const intervalDurations: Record<TimeInterval, { hours: number }> = {
  "last 6 hours": { hours: 6 },
  "last 12 hours": { hours: 12 },
  "last 3 days": { hours: 72 },
  "last week": { hours: 168 },
  "last month": { hours: 720 }
}
 
export function parseGameEndTime(
  gameEndTime: number | string | undefined
): number {
  if (typeof gameEndTime === "number") return gameEndTime

  if (typeof gameEndTime !== "string") return Number.NaN

  const parsedEndTime = DateTime.fromFormat(gameEndTime, "MMM d, yyyy", {
    zone: TIME_ZONE
  })

  if (!parsedEndTime.isValid) return Number.NaN

  return Math.floor(
    Math.min(parsedEndTime.endOf("day").toSeconds(), Date.now() / 1000)
  )
}
 
export function isWithinTimeInterval(
  endTime: number,
  timeInterval: TimeInterval
): boolean {
  const { start, end } = getTimeIntervalBounds(timeInterval)
 
  return endTime >= start && endTime <= end
}
 
export function getTimeIntervalBounds(timeInterval: TimeInterval): {
  start: number
  end: number
} {
  const now = DateTime.now().setZone(TIME_ZONE)
  const end = Math.floor(Date.now() / 1000)
  const start = Math.floor(
    now.minus(intervalDurations[timeInterval]).toSeconds()
  )
 
  return { start, end }
}