代码之家  ›  专栏  ›  技术社区  ›  Mathieu

如何清晰地分解两个几乎相似的函数

  •  0
  • Mathieu  · 技术社区  · 6 年前

    我有两个非常相似的函数内容,我想通过将代码变成一个函数来清晰地分解代码,但只有几行不同,更准确地说,其中一行比其他行多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+行分解为1个小的差异行,似乎可以改进。

    是否有推荐的方法可以做到这一点,可以使用类似于回调的方法来实现类似的操作?

    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 回复  |  直到 6 年前
        1
  •  1
  •   Bryan Ash    6 年前

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

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