From 29cac3515aef739271a9dbffdd9c83626da1753a Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Thu, 19 May 2016 19:37:11 -0700 Subject: [PATCH] refactor binary search. --- lib/bcoin/bst.js | 4 ++-- lib/bcoin/utils.js | 9 +++------ 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/lib/bcoin/bst.js b/lib/bcoin/bst.js index 5cc947cd..f4a10fa7 100644 --- a/lib/bcoin/bst.js +++ b/lib/bcoin/bst.js @@ -680,9 +680,9 @@ Iterator.prototype.seek = function seek(key) { if (typeof key === 'string') key = new Buffer(key, 'ascii'); - this.index = utils.binarySearch(this.items, key, true, function(a, b) { + this.index = utils.binarySearch(this.items, key, function(a, b) { return self.tree.compare(a.key, b); - }); + }, true); item = this.items[this.index]; diff --git a/lib/bcoin/utils.js b/lib/bcoin/utils.js index f6216edc..d3333d84 100644 --- a/lib/bcoin/utils.js +++ b/lib/bcoin/utils.js @@ -2413,14 +2413,11 @@ utils.revMap = function revMap(map) { * @returns {Number} Index. */ -utils.binarySearch = function binarySearch(items, key, insert, compare) { +utils.binarySearch = function binarySearch(items, key, compare, insert) { var start = 0; var end = items.length - 1; var pos, cmp; - if (!compare) - compare = utils.cmp; - while (start <= end) { pos = (start + end) >>> 1; cmp = compare(items[pos], key); @@ -2449,7 +2446,7 @@ utils.binarySearch = function binarySearch(items, key, insert, compare) { */ utils.binaryInsert = function binaryInsert(items, item, compare) { - var i = utils.binarySearch(items, item, true, compare); + var i = utils.binarySearch(items, item, compare, true); items.splice(i + 1, 0, item); return items.length; }; @@ -2463,7 +2460,7 @@ utils.binaryInsert = function binaryInsert(items, item, compare) { */ utils.binaryRemove = function binaryRemove(items, item, compare) { - var i = utils.binarySearch(items, item, false, compare); + var i = utils.binarySearch(items, item, compare, false); if (i === -1) return false; items.splice(i, 1);