Skip to content

Commit

Permalink
No need to sort and slice everything all the time, it can be done onc…
Browse files Browse the repository at this point in the history
…e at the end (#44)
  • Loading branch information
nazar-pc authored and tristanls committed Dec 4, 2017
1 parent fd83445 commit 64affd4
Showing 1 changed file with 7 additions and 9 deletions.
16 changes: 7 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -146,25 +146,23 @@ 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) {
var detNode = this._determineNode(node, id, bitIndex++)
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.
Expand Down

0 comments on commit 64affd4

Please sign in to comment.