mercredi 19 décembre 2018

How to execute a command repeatedly and execute another when error throws up without always checking for if conditions?

I have a code like there are only 2 scenarios - the data is of byte format / text format. Only at the kick start or very rarely I may receive text data. Hence i wrote the code like below :-

if (message.type === 'utf8') {
   console.log(message.utf8Data);
 }
if (message.type === 'binary') {
    dataStream.write(message.binaryData);
 }

Now I wish to refactor the code where by default it takes the binary type and proceeds to

dataStream.write(message.binaryData); 

and if the type is unmatched or error it should execute

console.log(message.utf8Data);

Please don't suggest any if else condition as it is expensive since dataStream gets execute a couple of hundred times, while text gets executed only or twice during the session. Doing a if check on every data format is cumbersome since every time we waste computation to know the data format.

I checked to execute try...catch on it. But I was not able to get proper results. Kindly someone suggests how to refactor this code to boost performance. Thank you!

Aucun commentaire:

Enregistrer un commentaire