fix(trie): trie returns invalid string when only the fist character matches, and the second doesn't match

This commit is contained in:
June Park 2024-09-03 00:49:53 +09:00
parent 7e45aaf609
commit 59cf685395
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');