Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.