refactor binary search.

This commit is contained in:
Christopher Jeffrey 2016-05-19 19:37:11 -07:00
parent a94a2a101d
commit 29cac3515a
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD
2 changed files with 5 additions and 8 deletions

View File

@ -680,9 +680,9 @@ Iterator.prototype.seek = function seek(key) {
if (typeof key === 'string') if (typeof key === 'string')
key = new Buffer(key, 'ascii'); 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); return self.tree.compare(a.key, b);
}); }, true);
item = this.items[this.index]; item = this.items[this.index];

View File

@ -2413,14 +2413,11 @@ utils.revMap = function revMap(map) {
* @returns {Number} Index. * @returns {Number} Index.
*/ */
utils.binarySearch = function binarySearch(items, key, insert, compare) { utils.binarySearch = function binarySearch(items, key, compare, insert) {
var start = 0; var start = 0;
var end = items.length - 1; var end = items.length - 1;
var pos, cmp; var pos, cmp;
if (!compare)
compare = utils.cmp;
while (start <= end) { while (start <= end) {
pos = (start + end) >>> 1; pos = (start + end) >>> 1;
cmp = compare(items[pos], key); cmp = compare(items[pos], key);
@ -2449,7 +2446,7 @@ utils.binarySearch = function binarySearch(items, key, insert, compare) {
*/ */
utils.binaryInsert = function binaryInsert(items, item, 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); items.splice(i + 1, 0, item);
return items.length; return items.length;
}; };
@ -2463,7 +2460,7 @@ utils.binaryInsert = function binaryInsert(items, item, compare) {
*/ */
utils.binaryRemove = function binaryRemove(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) if (i === -1)
return false; return false;
items.splice(i, 1); items.splice(i, 1);