Skip to content

Commit

Permalink
fix: strings with common prefix in suffixtree
Browse files Browse the repository at this point in the history
  • Loading branch information
Benricheson101 committed Oct 21, 2024
1 parent df78355 commit 7e6338b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
15 changes: 15 additions & 0 deletions lib/struct/suffixTree.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,19 @@ describe('struct/SuffixTree', () => {
deepStrictEqual(st.getChildren('an'), ['banana']);
deepStrictEqual(st.getChildren('a'), ['banana']);
});

it('inserts terms with common substrings', () => {
const st = new SuffixTree();
st.insert('caption');
st.insert('action');
st.insert('option');
st.insert('optional');

deepStrictEqual(st.getChildren('tion'), [
'optional',
'option',
'action',
'caption',
]);
});
});
10 changes: 8 additions & 2 deletions lib/struct/suffixTree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@ import {RadixTree} from './radixTree';

export class SuffixTree<T = undefined> {
readonly tree = new RadixTree<{data: T; term: string}>();
#terminatorNumber = 0;
#terminatorCharacter = '$';

insert(
...args: T extends undefined ? [term: string] : [term: string, data: T]
) {
const [term, data] = args as [term: string, data: T];
let [term, data] = args as [term: string, data: T];
const nodeData = {term, data};

for (let i = 0; i < term.length; i++) {
const termLen = term.length;

term += `${this.#terminatorCharacter}${this.#terminatorNumber++}`;

for (let i = 0; i < termLen; i++) {
this.tree.insert(term.slice(i), nodeData);
}

Expand Down

0 comments on commit 7e6338b

Please sign in to comment.