All files / apps/roomBooking/src/screens/Preview utils.ts

100% Statements 19/19
100% Branches 18/18
100% Functions 1/1
100% Lines 16/16

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                        2x       13x     11x   11x 10x 10x 10x   10x 2x     8x 8x   6x 6x   6x               1x     5x    
/**
 * Merge a date string and a time string into a single ISO date string.
 *
 * - If `dateInput` is not provided or is an invalid date, null is returned.
 * - If `timeStr` is not provided, the ISO date string is returned without the time.
 * - If `timeStr` is provided, the hours and minutes are extracted and set on the date.
 * - The resulting date is returned as an ISO date string.
 *
 * @param dateInput - The date string to merge with the time (e.g., "2025-11-07").
 * @param timeStr - The time string to merge with the date (e.g., "10:30").
 * @returns An ISO date string representing the merged date and time, or null if the date is invalid.
 */
export const mergeDateAndTimeToISO = (
  dateInput: string | Date | null | undefined,
  timeStr: string | null | undefined,
): string | null => {
  if (!dateInput) return null;
 
  const date =
    dateInput instanceof Date ? new Date(dateInput) : new Date(dateInput);
 
  if (Number.isNaN(date.getTime())) return null;
  const year = date.getFullYear();
  const month = date.getMonth();
  const day = date.getDate();
 
  if (!timeStr) {
    return new Date(year, month, day, 0, 0, 0).toISOString();
  }
 
  const parts = timeStr.split(':');
  if (parts.length < 2) return null;
 
  const hours = Number(parts[0]);
  const minutes = Number(parts[1]);
 
  if (
    !Number.isFinite(hours) ||
    !Number.isFinite(minutes) ||
    hours < 0 ||
    hours > 23 ||
    minutes < 0 ||
    minutes > 59
  ) {
    return null;
  }
 
  return new Date(year, month, day, hours, minutes, 0).toISOString();
};