All files / Hungry-Hippo-Game/src/components/Storage Storage.ts

89.47% Statements 17/19
87.5% Branches 7/8
100% Functions 1/1
89.47% Lines 17/19

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              1x 13x 13x 13x     13x     13x   13x   12x 13x   1x 1x   13x 13x 13x   13x   13x     13x
interface PlayerData {
  userId: string;
  role: string;
  color?: string | null;
  edge?: string | null;
}
 
export const updatePlayerInSessionStorage = (sessionId: string, playerData: PlayerData) => {
  try {
    const stored = localStorage.getItem('playerSessions');
    const allSessions = stored ? JSON.parse(stored) : {};
 
    // Get players for the current session, or start a new list
    const playersInSession = allSessions[sessionId] || [];
 
    // Find if this user already exists
    const playerIndex = playersInSession.findIndex((p: PlayerData) => p.userId === playerData.userId);
 
    if (playerIndex > -1) {
      // Player exists, update their data
      playersInSession[playerIndex] = { ...playersInSession[playerIndex], ...playerData };
    } else {
      // New player, add them
      playersInSession.push(playerData);
    }
 
    const latestSessionOnly = {
      [sessionId]: playersInSession
    };
 
    localStorage.setItem('playerSessions', JSON.stringify(latestSessionOnly));
 
  } catch (err) {
    console.error('Failed to update player session in storage', err);
  }
};