Merge pull request #15 from bitpay/add/funnel

Add simple funnel implementation
This commit is contained in:
Yemel Jardi 2015-02-20 15:55:15 -03:00
commit 3bb9d6a4d3
2 changed files with 115 additions and 0 deletions

45
lib/funnel.js Normal file
View File

@ -0,0 +1,45 @@
'use strict';
var bitcore = require('bitcore');
var $ = bitcore.util.preconditions;
var _ = bitcore.deps._;
var EventEmitter = require('events').EventEmitter;
var util = require('util');
function Funnel() {
this.handlers = {};
}
util.inherits(Funnel, EventEmitter);
Funnel.prototype.process = function(e) {
var queue = [];
var done = [];
queue.push(e);
while (queue.length !== 0) {
var event = queue.shift();
var handlers = this.handlers[event.constructor.name] || [];
handlers.forEach(function(handler) {
var responses = handler(event);
if (responses && responses.length > 0) {
queue = queue.concat(responses);
}
});
done.push(event);
}
done.forEach(function(event) {
//that.emit(event.name, event);
});
};
Funnel.prototype.register = function(clazz, handler) {
$.checkArgument(_.isFunction(handler));
var name = clazz.name;
this.handlers[name] = this.handlers[name] || [];
this.handlers[name].push(handler);
};
module.exports = Funnel;

70
test/funnel.js Normal file
View File

@ -0,0 +1,70 @@
'use strict';
var chai = require('chai');
var should = chai.should();
var sinon = require('sinon');
var Funnel = require('../lib/funnel');
describe('Funnel', function() {
it('instantiate', function() {
var f = new Funnel();
should.exist(f);
});
describe('process', function() {
function FooEvent() {}
function BarEvent() {}
var foo = new FooEvent();
var bar = new BarEvent();
foo.x = 2;
bar.y = 3;
it('no handlers registered', function() {
var f = new Funnel();
f.process.bind(f, foo).should.not.throw();
});
it('simple handler gets called', function(cb) {
var f = new Funnel();
f.register(FooEvent, function(e) {
e.x.should.equal(foo.x);
cb();
});
f.process(foo);
});
it('other event does not get called', function() {
var f = new Funnel();
var spy = sinon.spy();
f.register(FooEvent, spy);
f.process(bar);
spy.callCount.should.equal(0);
});
it('foo returns bar', function(cb) {
var f = new Funnel();
f.register(FooEvent, function(e) {
var b = new BarEvent();
b.y = e.x;
return [b];
});
f.register(BarEvent, function(e) {
e.y.should.equal(foo.x);
cb();
});
f.process(foo);
});
it('foo returns two bars', function() {
var f = new Funnel();
var spy = sinon.spy();
f.register(FooEvent, function() {
var b1 = new BarEvent();
var b2 = new BarEvent();
return [b1, b2];
});
f.register(BarEvent, spy);
f.process(foo);
spy.callCount.should.equal(2);
});
});
});