victorx
victorx

Reputation: 3559

How to combine multiple transform stream into one in nodejs

I have following code snippet

function func1(){
  return  makeReadbleStream1()
    .pipe(transformA)
    .pipe(transformB)
    .pipe(transformC)
    .pipe(X);
}

function func2(){
  return  makeReadbleStream2()
    .pipe(transformA)
    .pipe(transformB)
    .pipe(transformC)  
    .pipe(Y);
}

Function 1 and 2 shares a common logic of going through the transform A, B and C. Based on the principle of DRY, I think it's better to extract the logic into a function combinedTransformABC. However, it seems to me no obvious way to implement this function based on transformA, B and C such that I could refactor the code as below.

function func1(){
  return  makeReadbleStream1()
    .pipe(combinedTranformABC)
    .pipe(X);
}

function func2(){
  return  makeReadbleStream2()
    .pipe(combinedTranformABC)
    .pipe(Y);
}    

Any idea?

Upvotes: 7

Views: 2429

Answers (1)

codebox
codebox

Reputation: 20254

Why not just do this:

function applyTransforms(stream){
    return stream.pipe(transformA)
        .pipe(transformB)
        .pipe(transformC);
}
function func1(){
    return applyTransforms(makeReadbleStream1()).pipe(X);
}
function func2(){
    return applyTransforms(makeReadbleStream2()).pipe(Y);
}

Upvotes: 4

Related Questions