All files / memory-monitor/src/utils storage.ts

55.55% Statements 15/27
60% Branches 6/10
83.33% Functions 5/6
55.55% Lines 15/27

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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107        84x                           27x       27x 27x                               15x       15x 15x 15x                                                                     27x 27x 8x     19x 19x                           15x 15x          
/**
 * Check if we're running in a browser environment
 */
export function isBrowser(): boolean {
  return (
    typeof window !== "undefined" &&
    typeof window.localStorage !== "undefined"
  );
}
 
/**
 * Safely get item from localStorage
 * Returns null if not in browser or if key doesn't exist
 *
 * @param key - Storage key
 * @returns Stored value or null
 */
export function safeGetItem(key: string): string | null {
  Iif (!isBrowser()) {
    return null;
  }
 
  try {
    return window.localStorage.getItem(key);
  } catch {
    // Handle cases where localStorage is blocked (e.g., private browsing)
    return null;
  }
}
 
/**
 * Safely set item in localStorage
 * No-op if not in browser
 *
 * @param key - Storage key
 * @param value - Value to store
 * @returns Whether the operation succeeded
 */
export function safeSetItem(key: string, value: string): boolean {
  Iif (!isBrowser()) {
    return false;
  }
 
  try {
    window.localStorage.setItem(key, value);
    return true;
  } catch {
    // Handle cases where localStorage is full or blocked
    return false;
  }
}
 
/**
 * Safely remove item from localStorage
 * No-op if not in browser
 *
 * @param key - Storage key
 * @returns Whether the operation succeeded
 */
export function safeRemoveItem(key: string): boolean {
  if (!isBrowser()) {
    return false;
  }
 
  try {
    window.localStorage.removeItem(key);
    return true;
  } catch {
    return false;
  }
}
 
/**
 * Safely get and parse JSON from localStorage
 *
 * @param key - Storage key
 * @param defaultValue - Default value if not found or parse fails
 * @returns Parsed value or default
 */
export function safeGetJSON<T>(key: string, defaultValue: T): T {
  const item = safeGetItem(key);
  if (item === null) {
    return defaultValue;
  }
 
  try {
    return JSON.parse(item) as T;
  } catch {
    return defaultValue;
  }
}
 
/**
 * Safely stringify and set JSON to localStorage
 *
 * @param key - Storage key
 * @param value - Value to store
 * @returns Whether the operation succeeded
 */
export function safeSetJSON<T>(key: string, value: T): boolean {
  try {
    return safeSetItem(key, JSON.stringify(value));
  } catch {
    return false;
  }
}