Skip to content

Commit

Permalink
perf: improves 'contains' method in radix tree
Browse files Browse the repository at this point in the history
  • Loading branch information
micheleriva committed Oct 7, 2024
1 parent 8a381e3 commit 53dbfc5
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 11 deletions.
1 change: 1 addition & 0 deletions packages/orama/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
benchmark
1 change: 1 addition & 0 deletions packages/orama/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
"url": "https://github.com/askorama/orama"
},
"scripts": {
"benchmark": "node ../../benchmarks/index.js",
"predev": "rm -rf dist && mkdir dist",
"dev": "swc -s -w --extensions .ts,.cts -d dist src",
"prebuild": "npm run lint",
Expand Down
28 changes: 17 additions & 11 deletions packages/orama/src/trees/radix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,28 +260,34 @@ export class RadixNode {

public contains(term: string): boolean {
let node: RadixNode = this
let i = 0
const termLength = term.length
for (let i = 0; i < termLength; i++) {

while (i < termLength) {
const character = term[i]

if (node.c.has(character)) {
const childNode = node.c.get(character)!
const childNode = node.c.get(character)

if (childNode) {
const edgeLabel = childNode.s
const termSubstring = term.substring(i)
const commonPrefix = RadixNode.getCommonPrefix(edgeLabel, termSubstring)
const commonPrefixLength = commonPrefix.length

if (commonPrefixLength !== edgeLabel.length && commonPrefixLength !== termSubstring.length) {
const edgeLabelLength = edgeLabel.length
let j = 0

while (j < edgeLabelLength && i + j < termLength && edgeLabel[j] === term[i + j]) {
j++
}

if (j < edgeLabelLength) {
return false
}
i += childNode.s.length - 1

i += edgeLabelLength
node = childNode
} else {
return false
}
}
return true
}
}

public removeWord(term: string): boolean {
if (!term) {
Expand Down

0 comments on commit 53dbfc5

Please sign in to comment.