title: Conditionally chain functions in JavaScript
body: <p>I'm trying to refactor the following node.js code.</p>
  
  <p>Each case generates a thumbnail, chaining a different set of GraphicMagic transformation to an image.</p>
  
  <pre><code>switch(style.name) {
      case 'original':
          gm(response.Body)
              .setFormat('jpg').autoOrient().resize(style.w, style.h, style.option)
              .toBuffer(function(err, buffer) { if (err) { next(err); } else { next(null, buffer); } });
          break;
      case 'large':
          gm(response.Body)
              .setFormat('jpg').autoOrient().resize(style.w, style.h, style.option)
              .quality(style.quality)
              .strip().interlace('Plane')
              .toBuffer(function(err, buffer) { if (err) { next(err); } else { next(null, buffer); } });
          break;
      case 'medium':
          gm(response.Body)
              .setFormat('jpg').autoOrient().resize(style.w, style.h, style.option)
              .crop(style.w, style.h, style.crop.x_offset, style.crop.y_offset)
              .repage('+')
              .strip().interlace('Plane')
              .toBuffer(function(err, buffer) { if (err) { next(err); } else { next(null, buffer); } });
          break;
      case 'small':
          gm(response.Body)
              .setFormat('jpg').autoOrient().resize(style.w, style.h, style.option)
              .crop(style.w, style.h, style.crop.x_offset, style.crop.y_offset).repage('+')
              .quality(style.quality)
              .strip().interlace('Plane')
              .toBuffer(function(err, buffer) { if (err) { next(err); } else { next(null, buffer); } });
          break;
  }
  </code></pre>
  
  <p>However, all cases share a number of transformations at the beginning and the end of the chaining, so there's room for refactoring. I tried refactoring with the following approach, but the code seems incorrect:</p>
  
  <pre><code>gm(response.Body)
  .setFormat('jpg').autoOrient().resize(style.w, style.h, style.option, function(err, response) {
      if (style.name === 'original'){
          return response;
      } else if (style.name === 'large'){
          return response.quality(style.quality)
      } else if (style.name === 'medium'){
          return response.crop(style.w, style.h, style.crop.x_offset, style.crop.y_offset).repage('+')
      } else if (style.name === 'small'){
          return response.crop(style.w, style.h, style.crop.x_offset, style.crop.y_offset).repage('+').quality(style.quality)
      }
  }).(function(response) {
      return (stryle.name !== 'original') ? response.strip().interlace('Plane') : return response;
  }).(function(argument) {
      return response.toBuffer(function(err, buffer) { if (err) { next(err); } else { next(null, buffer); } });
  });
  </code></pre>