Skip to content

Commit

Permalink
Merge pull request #94 from sjunepark/trie
Browse files Browse the repository at this point in the history
fix(trie): trie returns invalid string when only the fist character m…
  • Loading branch information
zrwusa authored Sep 2, 2024
2 parents 7e45aaf + 59cf685 commit 022c337
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/data-structures/trie/trie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,12 @@ export class Trie<R = any> extends IterableElementBase<string, R, Trie<R>> {
if (prefix) {
for (const c of prefix) {
const nodeC = startNode.children.get(c);
if (nodeC) startNode = nodeC;
if (nodeC) {
startNode = nodeC;
} else {
// Early return if the whole prefix is not found
return [];
}
}
}

Expand Down
16 changes: 16 additions & 0 deletions test/unit/data-structures/trie/trie.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -836,6 +836,22 @@ describe('Trie operations', () => {
expect(words).toEqual(['apple', 'appetizer']);
});

it('Get no words when prefix not found, with no match from the first character', () => {
trie.add('apple');
trie.add('appetizer');
trie.add('banana');
const words = trie.getWords('cd');
expect(words).toEqual([]);
});

it('Get no words when prefix not found, with no match from the second character', () => {
trie.add('apple');
trie.add('appetizer');
trie.add('banana');
const words = trie.getWords('ab');
expect(words).toEqual([]);
});

it('Tree Height', () => {
trie.add('apple');
trie.add('banana');
Expand Down

0 comments on commit 022c337

Please sign in to comment.