All files / src/utils processingTimer.ts

100% Statements 24/24
100% Branches 6/6
100% Functions 3/3
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      1x 1x           1x 4x 4x 4x     4x 4x   4x     1x               1x 5x 5x 5x   4x 4x   6x 2x     2x     1x 1x      
// src/utils/processingTimer.ts
import { logger } from '../services/logger.client';
 
const PROCESSING_TIMES_KEY = 'flyerProcessingTimes';
const MAX_SAMPLES = 5;
 
/**
 * Records the duration of a flyer processing job in localStorage.
 * @param durationInSeconds - The processing time in seconds.
 */
export const recordProcessingTime = (durationInSeconds: number): void => {
  try {
    const storedTimes = localStorage.getItem(PROCESSING_TIMES_KEY);
    const times: number[] = storedTimes ? JSON.parse(storedTimes) : [];
 
    // Add the new time and keep only the last MAX_SAMPLES
    times.push(durationInSeconds);
    const recentTimes = times.slice(-MAX_SAMPLES);
 
    localStorage.setItem(PROCESSING_TIMES_KEY, JSON.stringify(recentTimes));
  } catch (error) {
    // Use the centralized logger for consistency.
    logger.error('Could not record processing time in localStorage.', { error });
  }
};
 
/**
 * Calculates the average processing time from stored durations.
 * @returns The average time in seconds, or a default of 45 seconds if no data exists.
 */
export const getAverageProcessingTime = (): number => {
  try {
    const storedTimes = localStorage.getItem(PROCESSING_TIMES_KEY);
    if (!storedTimes) return 45; // Default estimate if no history
 
    const times: number[] = JSON.parse(storedTimes);
    if (times.length === 0) return 45;
 
    const sum = times.reduce((acc, time) => acc + time, 0);
    const average = sum / times.length;
 
    // Return a rounded, reasonable number
    return Math.round(average);
  } catch (error) {
    // Use the centralized logger for consistency.
    logger.error('Could not get average processing time from localStorage.', { error });
    return 45; // Default on error
  }
};