useTrie is force-wired to work with declarative nature of React by returning a new instance on add/remove
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function reducer(state: ReducerState, action: TrieAction): ReducerState { | |
switch (action.type) { | |
case 'ADD': | |
state.trie.add(action.word); | |
return { ...state, trie: state.trie }; | |
case 'REMOVE': | |
state.trie.remove(action.word as string); | |
return { ...state, trie: state.trie }; | |
default: | |
return state; | |
} | |
} | |
function useTrie( | |
initialWords: Words, | |
isCaseInsensitive = true, | |
getText: (obj: any) => string = obj => obj | |
): ITrie { | |
const trie = new Trie(initialWords, isCaseInsensitive, getText); | |
const [state, dispatch] = React.useReducer(reducer, { trie, word: '' }); | |
function add(word: Word): void { | |
dispatch({ type: 'ADD', trie, word }); | |
} | |
function remove(word: string): void { | |
dispatch({ type: 'REMOVE', trie, word }); | |
} | |
return { ...state.trie, add, remove }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment