Skip to content

Commit 06a5aea

Browse files
committed
perf improvements and fixes
1 parent 3f2773a commit 06a5aea

File tree

1 file changed

+24
-19
lines changed

1 file changed

+24
-19
lines changed

bbtree.js

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,27 @@
22

33
if (typeof module !== 'undefined') module.exports = bbtree;
44

5-
function Node(key, left, right, level) {
5+
function Node(key, level, left, right) {
66
this.key = key;
7+
this.level = level;
78
this.left = left;
89
this.right = right;
9-
this.level = level;
1010
}
1111

12-
var bottom = new Node(null, null, null, 0);
12+
var bottom = new Node(null, 0);
1313
bottom.left = bottom;
1414
bottom.right = bottom;
1515

16+
function newNode(key) {
17+
return new Node(key, 1, bottom, bottom);
18+
}
19+
1620
function bbtree(compareFn) {
1721
// jshint validthis: true
1822
if (!(this instanceof bbtree)) return new bbtree(compareFn);
1923

2024
this._compare = compareFn || defaultCompare;
25+
this._path = [];
2126
}
2227

2328
bbtree.prototype = {
@@ -32,48 +37,48 @@ bbtree.prototype = {
3237
insert: function (key) {
3338

3439
var compare = this._compare,
35-
newNode = new Node(key, bottom, bottom, 1);
40+
node = this.root,
41+
path = this._path;
3642

37-
if (!this.root) {
38-
this.root = newNode;
43+
if (!node) {
44+
this.root = newNode(key);
3945
return this;
4046
}
4147

42-
var node = this.root,
43-
path = [];
48+
var k = 0;
4449

4550
while (true) {
4651
var c = compare(key, node.key);
4752
if (!c) return this;
4853

49-
path.push(node);
54+
path[k] = node;
55+
k++;
5056

5157
if (c < 0) {
52-
if (node.left === bottom) { node.left = newNode; break; }
58+
if (node.left === bottom) { node.left = newNode(key); break; }
5359
node = node.left;
5460

5561
} else {
56-
if (node.right === bottom) { node.right = newNode; break; }
62+
if (node.right === bottom) { node.right = newNode(key); break; }
5763
node = node.right;
5864
}
5965
}
6066

61-
this._rebalance(path);
67+
this._rebalance(path, k);
6268

6369
return this;
6470
},
6571

66-
_rebalance: function (path) {
72+
_rebalance: function (path, k) {
6773

68-
var rotated, node, parent, updated;
74+
var rotated, node, parent, updated, m = 0;
6975

70-
for (var i = path.length - 1; i >= 0; i--) {
76+
for (var i = k - 1; i >= 0; i--) {
7177
rotated = node = path[i];
72-
updated = false;
7378

7479
if (node.level === node.left.level && node.level === node.right.level) {
75-
node.level++;
7680
updated = true;
81+
node.level++;
7782

7883
} else {
7984
rotated = skew(node);
@@ -89,8 +94,8 @@ bbtree.prototype = {
8994

9095
} else this.root = rotated;
9196
}
92-
93-
if (!updated) break;
97+
if (!updated) m++;
98+
if (m === 2) break;
9499
}
95100
}
96101
};

0 commit comments

Comments
 (0)