Skip to content

Instantly share code, notes, and snippets.

@dance2die
Created March 23, 2019 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dance2die/168fcb4c7e85fbe8573c160b32520250 to your computer and use it in GitHub Desktop.
Save dance2die/168fcb4c7e85fbe8573c160b32520250 to your computer and use it in GitHub Desktop.
useTrie is force-wired to work with declarative nature of React by returning a new instance on add/remove
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