Skip to content

Commit

Permalink
⚡️ feat: optimize the search function of trie
Browse files Browse the repository at this point in the history
  • Loading branch information
niketpathak committed May 19, 2024
1 parent ee858e2 commit d0aa5ae
Showing 1 changed file with 8 additions and 7 deletions.
15 changes: 8 additions & 7 deletions src/trie/trie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,10 @@ export const Trie: TrieType<any> = (config = {}) => {
function find(prefix: string): Dictionary {
let node = root;
let matches: Dictionary = {};
let token;

// traverse the root until you reach the end of prefix
for (let i = 0, l = prefix.length; i < l; i++) {
token = prefix[i]; // each letter of search string
node = node[token] as Record<string, unknown>;
for (const char of prefix) {
node = node?.[char] as Record<string, unknown>;
if (typeof node === 'undefined') return {};
}

Expand All @@ -74,12 +72,15 @@ export const Trie: TrieType<any> = (config = {}) => {

while (stack.length) {
current = stack.pop() as { node: Record<string, unknown>; prefix: string };
node = current.node;
prefix = current.prefix;
const { node, prefix } = current;

for (const k in node) {
if (k === SENTINEL) {
Object.assign(matches, node[SENTINEL]);
// Object.assign(matches, node[SENTINEL]);
const results = node[SENTINEL] as Dictionary;
for (const resultKey in results) {
matches[resultKey] = results[resultKey];
}
} else {
stack.push({ node: node[k] as Record<string, unknown>, prefix: prefix + k });
}
Expand Down

0 comments on commit d0aa5ae

Please sign in to comment.