The idea would be to define a set of objects which define your event sequences and when you get the first event that matches, you copy that sequence and then pop elements of the array until you have no more elements. If you encounter an event which doesn't match, you reset your current buffer.
var events = [
{ sequence : ['event 1', 'event 2', 'event4']
handler: firstSequenceHandler
},
{ sequence : ['event 3', 'event 2']
handler: secondSequenceHandler
}
];
Subscribe to your event stream:
var eventbuffer;
var handler;
on('data', function(event){
if(eventbuffer){ // we already have started a sequence:
var expectedEvent = eventbuffer.pop(); // get the next expected event
if(expectedEvent === event && eventbuffer.length===0)
return handler();
else{
// reset buffer:
eventbuffer = null;
handler = null;
}
}
// check if the event is in your list of events as the first item.
// if so
eventbuffer = event.sequence.slice(0); // copy the sequence.
handler = event.handler;
eventbuffer.pop(); // remove the first element as you found it.
));