All files / src/hooks helpers.ts

21.87% Statements 7/32
14.28% Branches 4/28
28.57% Functions 2/7
21.42% Lines 6/28

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 54 55            120x                                                                             120x     120x 466x 162x 28566x      
// This helper function checks if an object (whose at least one of its properties is required by BE) has one of the properties set.
// If one of the property is set but the others are not, then it sets the non-set properties to null.
 
import { country_dial_codes } from "../utils/country_dial_codes";
 
// Until BE makes modifications
export const notSetButRequired = (value: unknown): unknown => {
  if (typeof value === "string") {
    return value.trim() === "" ? null : value;
  }
  if (typeof value === "object" && value !== null) {
    const nonNullKeys = Object.keys(value).filter((key) => (value as any)[key] !== undefined);
    if (nonNullKeys.length > 0) {
      const emptyProps = Object.keys(value).reduce<Record<string, any>>(
        (acc, key) => {
          const val = (value as any)[key];
          if (typeof val === "string" && val.trim() === "") {
            return { ...acc, [key]: null };
          }
          if (val === undefined) {
            return { ...acc, [key]: null };
          }
          // Check nested objects
          if (typeof val === "object" && val !== null) {
            const nestedEmpty = notSetButRequired(val);
            if (nestedEmpty === null) {
              return acc;
            }
            return { ...acc, [key]: nestedEmpty };
          }
          return acc;
        },
        {},
      );
      const merged = { ...value, ...emptyProps };
      if (Object.values(merged).every((val) => val === null)) {
        return null;
      }
      return merged;
    }
  }
  return null;
};
 
// For Yup validation (if any of the address fields is filled, makes all the others required)
export const isAnyTruthy = (...values: string[]) => values.some(Boolean);
 
// US -> United States
export const toCountryName = (code?: string): string => {
  if (!code) return "";
  return (
    country_dial_codes.find((country) => code === country.code)?.name || ""
  );
};