Photo by Jamie Street on Unsplash – “trie” is from “Retrieval” thus the cute 🐶 “Retriever”
I’ve released @cshooks/usetrie.
It’s a React Hook for Typeahead/autocompletion.
@cshooks/hooks will be the home 🏠 of Computer Science data structures/algorithms related hooks.
🤔 Why?
When you have a list of texts you want to match by prefix, you have to match each text in an array one by one, which can be time consuming.
Trie is a data structure, which stores text in a tree, which enables a fast prefix look up.
And useTrie
works as a facade to enable fast prefix search.
🔧 How?
Check out the README file, which explains the usage in detail.
Here are some quick demo Sandboxes for the impatients.
➕ Additional Info
I’ve created this initially for academic purposes to learn Trie data structure so Trie
class is imperative and useTrie
hook was forced to fit to work with declarative nature of React as shown below, which is not ideal.
https://github.com/cshooks/hooks/blob/master/packages/useTrie/src/index.ts#L191
I’d really appreciate any feedback on how I can improve the code base.
I will share in the next post what I’ve learned and failures.
And I plan to add other hooks returning Min/Max heaps & Permutations.
🏔 Resources
- NPM – @cshooks/usetrie
- Source Code on GitHub
- License – MIT
The post @cshooks/usetrie, A React Hook for Typeahead/Autocomplete appeared first on Sung's Technical Blog.
Top comments (7)
Will check out the repo this week Sung. Just back from vacation, so my body is back from the beach but not my brain. 😉
OK, just glanced at the code quickly, so just a few comments about improving the TypeScript code. 😉
Can be written using TypeScript's built-in generic
Record
type.You don't need to specify the
string
type as it's inferred by the default value''
.getText
, you can create a type and reuse it instead of using(obj: any) => string;
in multiple places. Also you could rewrite this type asAnd extend
T
so that it respects some criteria.public
keyword. It's the default.type Words = Word[];
, I wouldn't bother with this type. Just useWord[]
.😮...
Those are great tips, Nick 👊
Regarding the
public
keyword, I was confused coming from C#, in which access modifiers areprivate
by default 😅 (now I know it's public).And
Words
does seem unnecessary asWord[]
shows the intention (of word being an array type) better 😂.It seems like I need to get used to built-in types from those tips.
Thank you for providing me a way to improve the code-base, Nick.
No problem. Glad to see you're having fun in TypeScript land. 🎡
Thank you for the warm welcome.
It's been fun & need to unlearn what I know first 😉
Great job!
Thanks, Joe~ 👊