Skip to content

Commit

Permalink
More counter fixes
Browse files Browse the repository at this point in the history
* Handle counter wrapping properly when val > 1.
* Prevent counter from being decremented below 0.
  • Loading branch information
Michael S. Fischer committed Jul 6, 2011
1 parent 7af921b commit 5672088
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions metrics/counter.js
Expand Up @@ -14,17 +14,19 @@ var Counter = module.exports = function Counter() {

Counter.prototype.inc = function(val) {
if (!val) { val = 1; }
if (this.count === MAX_COUNTER_VALUE) {
this.count = 0;
} else {
this.count += val;
this.count += val;
// Wrap counter if necessary.
if (this.count > MAX_COUNTER_VALUE) {
this.count -= MAX_COUNTER_VALUE;
}
}

Counter.prototype.dec = function(val) {
if (!val) { val = 1; }
if (this.count > 0) {
this.count -= val;
this.count -= val;
// Prevent counter from being decremented below zero.
if (this.count < 0) {
this.count = 0;
}
}

Expand Down

0 comments on commit 5672088

Please sign in to comment.