All files / src/utils timestampInPast.ts

88.88% Statements 16/18
87.5% Branches 7/8
100% Functions 3/3
88.88% Lines 16/18

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      1x 65x 65x           1x 64x 64x   64x     1x 1x         1x 64x 64x 64x 64x 64x 64x  
/**
 * Returns the current Unix time in seconds.
 */
export function nowUnixSeconds(): number {
  return Math.floor(Date.now() / 1000);
}
 
/**
 * Normalizes a timestamp to Unix seconds.
 * @returns second timestamp or null for invalid input
 */
export function normalizeToUnixSeconds(raw: unknown): number | null {
  const numericTimestamp = Number(raw);
  if (!Number.isFinite(numericTimestamp)) return null;
  // Current ms epoch values ~1.6e12–1.9e12
  if (numericTimestamp > 1e12) {
    return Math.floor(numericTimestamp / 1000);
  }
  return Math.floor(numericTimestamp);
}
 
/**
 * Checks whether a timestamp is in the past (>= now).
 */
export function isExpired(
  ts: unknown,
  nowSec: number = nowUnixSeconds()
): boolean {
  const sec = normalizeToUnixSeconds(ts);
  return sec !== null && nowSec >= sec;
}