Merge pull request #94 from sjunepark/trie

fix(trie): trie returns invalid string when only the fist character m…
This commit is contained in:
zrwusa 2024-09-03 09:31:09 +12:00 committed by GitHub
commit 022c337ca9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 22 additions and 1 deletions

View file

@ -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 [];
}
}
}

View file

@ -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');