Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(tree): avoid recursive calls #2755

Merged
merged 1 commit into from
Feb 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 29 additions & 21 deletions lib/core/tree.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,31 +36,39 @@ class TstNode {
/**
* @param {Uint8Array} key
* @param {any} value
* @param {number} index
*/
add (key, value, index) {
if (index === undefined || index >= key.length) {
add (key, value) {
const length = key.length
if (length === 0) {
throw new TypeError('Unreachable')
}
const code = key[index]
if (this.code === code) {
if (key.length === ++index) {
this.value = value
} else if (this.middle !== null) {
this.middle.add(key, value, index)
} else {
this.middle = new TstNode(key, value, index)
}
} else if (this.code < code) {
if (this.left !== null) {
this.left.add(key, value, index)
let index = 0
let node = this
while (true) {
const code = key[index]
if (node.code === code) {
if (length === ++index) {
node.value = value
break
} else if (node.middle !== null) {
node = node.middle
} else {
node.middle = new TstNode(key, value, index)
break
}
} else if (node.code < code) {
if (node.left !== null) {
node = node.left
} else {
node.left = new TstNode(key, value, index)
break
}
} else if (node.right !== null) {
node = node.right
} else {
this.left = new TstNode(key, value, index)
node.right = new TstNode(key, value, index)
break
}
} else if (this.right !== null) {
this.right.add(key, value, index)
} else {
this.right = new TstNode(key, value, index)
}
}

Expand Down Expand Up @@ -107,7 +115,7 @@ class TernarySearchTree {
if (this.node === null) {
this.node = new TstNode(key, value, 0)
} else {
this.node.add(key, value, 0)
this.node.add(key, value)
}
}

Expand Down
Loading