Q:

ifElse statement with state?

Background
I am making an app that receives messages from several devices. Upon receiving a messages an event is fired with the given message:
on( "data", message => {
    //doSomething
} );

Challenge
This function receives two types of messages: A and B:

message A has the id of the device
message B has some info about a deivce

My first approach to dealing with this was the following:
const { ifElse } = require("ramda");

const evalData = ifElse(
    isTypeA,        // Returns true if type A, false otherwise
    evalTypeA,      // Returns device Id
    evalTypeB       // Processes data in message and returns bytes read
);

on( "data", evalData );

Problem
The problem here is that messages of type B don't have the Id of the device they belong to. So to properly process the message I need the deviceId that evalTypeA returned in a previous message. 
My idea to tackle this was to pass the Id to evalTypeB:
const evalData = messages => {
    let id = undefined;
    id = ifElse(
        isTypeA,        // Returns true if type A, false otherwise
        evalTypeA,      // Returns device Id
        evalTypeB( id )       // Processes data in message and returns bytes read
    )( message );
} 

The problem here is that this wouldn't work! evalTypeB also returns a number and then I would have no idea if what the ifElse expression is given me is a number of bytes read or an Id!
Question
How would you solve this without mutation and side effects?

A:

By definition, a pure function that is called repeated times as the callback for on('data', callback) can not keep track of state from previous calls.
With that in mind, there are a couple of options to consider to help try to minimise or localise the side-effects:

Close over the state, keeping the logic free of side-effects:

const processMsg = ifElse(isTypeA, evalTypeA, evalTypeB)

const handler = initialState => {
  let state = initialState
  return msg => {
      state = processMsg(state, msg)
  }
}

on('data', handler(42))

Recursively attach a new handler that will only be called once for each message at the end of each call, limiting the effects to the handler registration (this assumes something like once is supported by the event emitter):

const processMsg = ifElse(isTypeA, evalTypeA, evalTypeB)

const handler = state => msg =>
  once('data', handler(processMsg(state, msg)))

once('data', handler(42))

