Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FindClosest function added to treebase.js #32

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 34 additions & 0 deletions lib/treebase.js
Expand Up @@ -24,6 +24,40 @@ TreeBase.prototype.find = function(data) {
return null;
};

// returns node data closest to supplied value.
TreeBase.prototype.findClosest = function(data){
var res = this._root;
var lastSmallerNode = null;
var lastSmallerC = null;
var lastLargerNode = null;
var lastLargerC = null;

while(res !== null){
var c = this._comparator(data, res.data);
if(c === 0) {
return res.data;
}
else {
if(c < 0) {
lastLargerC = c;
lastLargerNode = res;
}
else if(c > 0){
lastSmallerC = c;
lastSmallerNode = res;
}
res = res.get_child(c > 0);
}
}

// will reach here only if it reaches a null node
if(lastSmallerC === null && lastLargerC === null) return null; // nothing in rbtree
var absSmall = Math.abs(lastSmallerC);
var absLarge = Math.abs(lastLargerC);
if (absSmall == absLarge) return lastSmallerNode.data;
return absSmall < absLarge ? lastSmallerNode.data : lastLargerNode.data;
};

// returns iterator to node if found, null otherwise
TreeBase.prototype.findIter = function(data) {
var res = this._root;
Expand Down