All files / repo/src/stores useGameHistoryStore.ts

94.87% Statements 37/39
66.66% Branches 8/12
100% Functions 4/4
94.87% Lines 37/39

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  1x 1x   1x   1x 4x   4x 1x 1x 1x 1x     1x   4x 13x 13x 13x 13x   4x 1x 1x 1x   4x 14x 14x   4x 1x 1x 1x 1x 4x   4x 4x 4x 4x 4x 4x 4x 4x  
import type { GameHistoryEntry } from '@/components/GameCanvas/GameCanvas.types';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
 
const STORAGE_KEY = 'memory-game-history';
 
export const useGameHistoryStore = defineStore('gameHistory', () => {
  const history = ref<GameHistoryEntry[]>([]);
 
  function loadFromStorage() {
    try {
      const raw = localStorage.getItem(STORAGE_KEY);
      history.value = raw ? JSON.parse(raw) : [];
    } catch {
      history.value = [];
    }
  }
 
  function addEntry(entry: GameHistoryEntry) {
    history.value.unshift(entry);
    history.value = history.value.slice(0, 10);
    saveToStorage();
  }
 
  function clearHistory() {
    history.value = [];
    saveToStorage();
  }
 
  function saveToStorage() {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(history.value));
  }
 
  const stats = computed(() => {
    const games = history.value.length;
    const avgTime = games ? Math.round(history.value.reduce((a, e) => a + e.time, 0) / games) : 0;
    const avgMoves = games ? Math.round(history.value.reduce((a, e) => a + e.moves, 0) / games) : 0;
    return { games, avgTime, avgMoves };
  });
 
  return {
    history,
    addEntry,
    clearHistory,
    loadFromStorage,
    stats,
  };
});