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

Issue-#4: Add Support for saving state #5

Open
wants to merge 2 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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions tdigest.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,25 @@ function TDigest(delta, K, CX) {
this.reset();
}

TDigest.prototype.load = function( tdObject ) {
// given a javascript object, re-initialize ourselves
//
// save: is not implemented as JSON.stringify(TDigest object) works just fine
//

//clear & reload
this.centroids.clear();
this._traverse(tdObject.centroids._root);

// init all internal variables based on object
this.delta = tdObject.delta;
this.K = tdObject.K;
this.CX = tdObject.CX;
this.n = tdObject.n;
this.nreset = tdObject.nreset;
this.last_cumulate = tdObject.last_cumulate;
};

TDigest.prototype.reset = function() {
// prepare to digest new points.
//
Expand Down Expand Up @@ -141,6 +160,25 @@ TDigest.prototype.find_nearest = function(x) {
}
};

TDigest.prototype._traverse = function(obj) {
if ( obj.left ) {
this._traverse(obj.left);
}
if ( obj.right ) {
this._traverse(obj.right);
}
if (obj.data) {
this._insert_centroid(obj.data);
}
}

TDigest.prototype._insert_centroid = function(obj) {
// insert a centroid into the digest
//
this.centroids.insert(obj);
this.n += obj.n;
};

TDigest.prototype._new_centroid = function(x, n, cumn) {
// create and insert a new centroid into the digest (don't update
// cumulatives).
Expand Down Expand Up @@ -294,6 +332,8 @@ TDigest.prototype._percentile = function(p) {
return undefined;
}
this._cumulate(true); // be sure cumns are exact
var min = this.centroids.min();
var max = this.centroids.max();
var h = this.n * p;
var bound = this.bound_mean_cumn(h);
var lower = bound[0], upper = bound[1];
Expand Down