Skip to content

Commit

Permalink
Avoid duplicating code in removeHit
Browse files Browse the repository at this point in the history
  • Loading branch information
tonyskn committed Jan 29, 2014
1 parent 7941c1d commit c0a7b4f
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 20 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@ You can find basic usage examples in `examples`. This module also powers a [real
.recordHit('another_stats_key', timestamp2, increment)
.exec();

// Removing hits
//
// It's also possible to decrement the hits counter for
// some key
ts.removeHit('your_stats_key', [timestamp]).exec();

// Querying statistics
//
Expand Down
1 change: 0 additions & 1 deletion examples/hitter.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ setTimeout(function hit() {

// Just decrement the 'key' counter every once in a while
// with some delay to try again

setTimeout(function removeHit() {
ts.removeHit(key)
.exec(function() {
Expand Down
26 changes: 7 additions & 19 deletions src/timeseries.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,29 +57,17 @@ TimeSeries.prototype.recordHit = function(key, timestamp, increment) {
* stats keys you provide
*
* "timestamp" defaults to the current time
* "decrement" defaults to 1
* "decrement" defaults to -1
*
* ts.removeHit('your_stats_key')
* .removeHit('another_stats_key', timestamp)
* .removeHit('another_stats_key', timestamp2, decrement)
* …
* .exec();
* .removeHit('another_stats_key', timestamp)
* .removeHit('another_stats_key', timestamp2, decrement)
*
* .exec();
*/
TimeSeries.prototype.removeHit = function(key, timestamp, decrement) {
var self = this;

Object.keys(this.granularities).forEach(function(gran) {
var properties = self.granularities[gran],
keyTimestamp = getRoundedTime(properties.ttl, timestamp),
tmpKey = [self.keyBase, key, gran, keyTimestamp].join(':'),
hitTimestamp = getRoundedTime(properties.duration, timestamp);

self.pendingMulti.hincrby(tmpKey, hitTimestamp, Math.floor(decrement || -1));
self.pendingMulti.expireat(tmpKey, keyTimestamp + 2 * properties.ttl);
});

return this;
}
return this.recordHit(key, timestamp, -(decrement || 1));
};

/**
* Execute the current pending redis multi
Expand Down

0 comments on commit c0a7b4f

Please sign in to comment.