All files / src/useStates useDateState.ts

100% Statements 15/15
100% Branches 12/12
100% Functions 2/2
100% Lines 15/15

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        3x 2x 2x   1x 1x   3x 1x   2x                             7x 5x 2x 1x   1x   7x   7x                
import { Dispatch, useReducer } from "react";
function dateReduction(prev: Date, next: Date | number): Date {
  let nextDateTime: number;
  let nextDate: Date;
  if (typeof next === "number") {
    nextDateTime = next;
    nextDate = new Date(next);
  } else {
    nextDateTime = next.getTime();
    nextDate = next;
  }
  if (prev.getTime() === nextDateTime) {
    return prev;
  } else {
    return nextDate;
  }
}
 
/**
 * This simulates the logic of useState but the input is a Date or a number representing the instant.
 * It will always provide a Date and may NOT be null.  However, the initial state if it is a function must
 * be return a Date.
 *
 * Since null is not a supported value, designate a constant like `Date(0)` to represent an undefined state.
 */
export function useDateState(
  initialState: Date | number | (() => Date)
): [Date, Dispatch<Date | number>] {
  let theInitialState: Date;
  if (typeof initialState === "number") {
    theInitialState = new Date(initialState);
  } else if (typeof initialState === "function") {
    theInitialState = null as unknown as Date;
  } else {
    theInitialState = initialState;
  }
  const initialStateIsFunction = typeof initialState === "function";
 
  return useReducer(
    dateReduction,
    initialStateIsFunction ? (null as unknown as Date) : theInitialState,
    initialStateIsFunction
      ? (initialState as () => Date)
      : (undefined as unknown as () => Date)
  );
}