如何清晰地分解两个几乎相似的功能

时间:2018-05-09 14:30:54

标签: javascript

我有两个非常相似的函数内容,我想通过将代码简单地分解为一个单独的函数来分解代码,但只有几行不同,更确切地说,其中一行有3行代码而不是其他

function doStuffForFacebook() { 
  var example = "toto"
  //about 7 lines of code

  resizeScale = 1
}

functiondoStuffforYoutube() {
  var example = "toto"
  //the VERY SAME 7 lines of code as those inside doStuffForFacebook()

  //the 3 lines which are different from above
  if ( typeof cryptoVideoX !== "undefined" && cryptoVideoX !== null && cryptoVideoX !== 0 ) {
     var vidRatio = cryptoVideoX / netVideoY;
  } else { //no crypto video add-on by source
      var vidRatio = netVideoRatio;
  }
  var manually_recalculated_width_to_have_full_screen_height_video = Math.round(vidRatio * winHeight);// fb only accepts rounded values
            $fbPlayer.attr('data-width', manually_recalculated_width_to_have_full_screen_height_video );

  resizeScale = 1
}

我真的很想分解为重复所有这些长7+行只是为了一小段差异似乎是可以改进的。

有没有办法建议这样做,也许使用类似于回调的东西,可以做类似的事情?

function doStuffForFacebook() { 
  resizeVideo(null);//nil because here no callback is necessary
}

functiondoStuffforYoutube() {
  resizeVideo(addSomeCodeCallback);
}
function resizeVideo(callback) {
  var example = "toto"
  //the 7 lines of common CODE
  callback();          
  resizeScale = 1
}
function addSomeCodeCallback() {
  if ( typeof cryptoVideoX !== "undefined" && cryptoVideoX !== null && cryptoVideoX !== 0 ) {
     var vidRatio = cryptoVideoX / netVideoY;
  } else { //no crypto video add-on by source
      var vidRatio = netVideoRatio;
  }
  var manually_recalculated_width_to_have_full_screen_height_video = Math.round(vidRatio * winHeight);// fb only accepts rounded values
            $fbPlayer.attr('data-width', 
  manually_recalculated_width_to_have_full_screen_height_video );
}

我知道我可以,但我不愿意:为之前的事物创建功能,为之后的事情创建另一个功能,因为它们更合乎逻辑而不是因为它们属于到大的if / else块。

如何正确地遵守javascript最佳做法?

1 个答案:

答案 0 :(得分:1)

您可以为回调参数提供默认的空函数:

function resizeVideo(callback = function(){}) {
  ...
  callback() 
  ...
}