| 
1 | 1 | import { useCallback } from 'react'  | 
2 | 2 | 
 
  | 
3 |  | -import { STEPS_LIMIT } from 'constants/puzzle.constants'  | 
4 |  | -import { ST_HISTORY } from 'constants/storage.constants'  | 
5 | 3 | import { useLocalStorage } from 'hooks/useLocalStorage'  | 
6 |  | -import { CellState } from 'models/Puzzle'  | 
7 | 4 | 
 
  | 
8 |  | -type Step = [number, number, CellState]  | 
9 |  | - | 
10 |  | -type UseHistoryType = {  | 
 | 5 | +type UseHistoryType<T> = {  | 
11 | 6 |   hasHistory: boolean  | 
12 |  | -  addStep: (row: number, col: number, state: CellState) => void  | 
13 |  | -  getStep: () => Step | null  | 
14 |  | -  cleanSteps: () => void  | 
 | 7 | +  addEntry: (entry: T) => void  | 
 | 8 | +  getEntry: () => T | null  | 
 | 9 | +  cleanHistory: () => void  | 
15 | 10 | }  | 
16 | 11 | 
 
  | 
17 |  | -export const useHistory = (): UseHistoryType => {  | 
18 |  | -  const [history, setHistory, cleanHistory] = useLocalStorage(ST_HISTORY, [] as Step[])  | 
 | 12 | +export const useHistory = <T>(  | 
 | 13 | +  storageId: string,  | 
 | 14 | +  entriesLimit: number  | 
 | 15 | +): UseHistoryType<T> => {  | 
 | 16 | +  const [history, setHistory, clearHistory] = useLocalStorage(storageId, [] as T[])  | 
19 | 17 | 
 
  | 
20 | 18 |   const hasHistory = history.length > 0  | 
21 | 19 | 
 
  | 
22 |  | -  const addStep = useCallback(  | 
23 |  | -    (row: number, col: number, state: CellState) => {  | 
24 |  | -      const newStep = [row, col, state] as Step  | 
25 |  | -      setHistory((steps) => [newStep, ...steps].slice(0, STEPS_LIMIT))  | 
 | 20 | +  const addEntry = useCallback(  | 
 | 21 | +    (newEntry: T) => {  | 
 | 22 | +      setHistory((entries) => [newEntry, ...entries].slice(0, entriesLimit))  | 
26 | 23 |     },  | 
27 |  | -    [setHistory]  | 
 | 24 | +    [entriesLimit, setHistory]  | 
28 | 25 |   )  | 
29 | 26 | 
 
  | 
30 |  | -  const getStep = useCallback(() => {  | 
 | 27 | +  const getEntry = useCallback(() => {  | 
31 | 28 |     if (!hasHistory) return null  | 
32 |  | -    const [step, ...nextHistory] = history  | 
 | 29 | +    const [entry, ...nextHistory] = history  | 
33 | 30 |     setHistory(nextHistory)  | 
34 |  | -    return step as Step  | 
 | 31 | +    return entry as T  | 
35 | 32 |   }, [hasHistory, history, setHistory])  | 
36 | 33 | 
 
  | 
37 |  | -  const cleanSteps = useCallback(() => {  | 
38 |  | -    cleanHistory()  | 
 | 34 | +  const cleanHistory = useCallback(() => {  | 
 | 35 | +    clearHistory()  | 
39 | 36 |     setHistory([])  | 
40 |  | -  }, [cleanHistory, setHistory])  | 
 | 37 | +  }, [clearHistory, setHistory])  | 
41 | 38 | 
 
  | 
42 |  | -  return { hasHistory, addStep, getStep, cleanSteps }  | 
 | 39 | +  return { hasHistory, addEntry, getEntry, cleanHistory }  | 
43 | 40 | }  | 
0 commit comments