Skip to content

Commit

Permalink
does not work, but tired
Browse files Browse the repository at this point in the history
  • Loading branch information
pgte committed Mar 24, 2013
1 parent 70c1cb3 commit b4bc997
Show file tree
Hide file tree
Showing 5 changed files with 108 additions and 0 deletions.
2 changes: 2 additions & 0 deletions .gitignore
@@ -0,0 +1,2 @@
node_modules
.DS_Store
3 changes: 3 additions & 0 deletions .travis.yml
@@ -0,0 +1,3 @@
language: node_js
node_js:
- 0.10
59 changes: 59 additions & 0 deletions index.js
@@ -0,0 +1,59 @@
var EventEmitter = require('events').EventEmitter;
var now = require('microtime').now;

module.exports =
function FrequencyMeter(targetInterval) {
if (! targetInterval) targetInterval = 1000;

var count = 0;
var maxCount = 10;
var start = now();
var frequency = 0;
var period = targetInterval;
var timeout;

var ee = new EventEmitter();

ee.happened =
function happened() {
count ++;
if (count == maxCount) cycle();
};

ee.end =
function end() {
clearTimeout(timeout);
};

schedule();

return ee;

//// ------

function cycle(fromTimeout) {
clearTimeout(timeout);
var t = now();
period = (t - start) / 1000;
if (fromTimeout) period = period / 2;

if (count === 0) {
frequency = 0;
period = targetInterval / 2;
} else {
frequency = (period / 1000) / count;
}

schedule();

ee.emit('frequency', frequency);

count = 0;
start = t;
}

function schedule() {
timeout = setTimeout(cycle, period * 2, true);
}

}
26 changes: 26 additions & 0 deletions package.json
@@ -0,0 +1,26 @@
{
"name": "frequency-meter",
"version": "0.0.1",
"description": "Measures event frequency",
"main": "index.js",
"scripts": {
"test": "node test/meter.js"
},
"repository": {
"type": "git",
"url": "git@github.com:pgte/frequency-meter.git"
},
"dependencies": {
"microtime": "*"
},
"devDependencies": {
"tap": "*"
},
"keywords": [
"frequency",
"measure",
"event"
],
"author": "pgte",
"license": "MIT"
}
18 changes: 18 additions & 0 deletions tests/meter.js
@@ -0,0 +1,18 @@
var test = require('tap').test;
var Meter = require('..');

test('emits 0 when no activity', function(t) {
t.plan(10);
var m = Meter(100);
var count = 0;

m.on('frequency', function(f) {
console.log('f:', f);
count ++;
t.strictEqual(f, 0);
if (count == 10) {
console.log('endindind');
m.end();
}
});
});

0 comments on commit b4bc997

Please sign in to comment.