Skip to content

Commit

Permalink
perf(tree): avoid recursive calls (nodejs#2755)
Browse files Browse the repository at this point in the history
  • Loading branch information
tsctx authored and crysmags committed Feb 27, 2024
1 parent aa08ee1 commit 85a9304
Showing 1 changed file with 29 additions and 21 deletions.
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

0 comments on commit 85a9304

Please sign in to comment.