From 64affd41cf6d4f97d53d64dad4b20c6ee881da65 Mon Sep 17 00:00:00 2001 From: Nazar Mokrynskyi Date: Mon, 4 Dec 2017 18:59:50 +0200 Subject: [PATCH] No need to sort and slice everything all the time, it can be done once at the end (#44) --- index.js | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index d5d32fa..297041a 100644 --- a/index.js +++ b/index.js @@ -146,13 +146,6 @@ KBucket.prototype.closest = function (id, n) { if (typeof n !== 'number' || isNaN(n) || n <= 0) throw new TypeError('n is not positive number') var contacts = [] - var self = this - function sort (contacts) { - return contacts.slice().sort(function (a, b) { - return self.distance(a.id, id) - self.distance(b.id, id) - }) - } - for (var nodes = [ this.root ], bitIndex = 0; nodes.length > 0 && contacts.length < n;) { var node = nodes.pop() if (node.contacts === null) { @@ -160,11 +153,16 @@ KBucket.prototype.closest = function (id, n) { nodes.push(node.left === detNode ? node.right : node.left) nodes.push(detNode) } else { - contacts = contacts.concat(sort(node.contacts)).slice(0, n) + contacts = contacts.concat(node.contacts) } } - return contacts + var self = this + function compare (a, b) { + return self.distance(a.id, id) - self.distance(b.id, id) + } + + return contacts.sort(compare).slice(0, n) } // Counts the number of contacts recursively.