如何在Angularjs中重构闭包中的重复代码

How to refactor duplicate code in a closure in Angularjs?

本文关键字:代码 闭包 重构 Angularjs      更新时间:2023-09-26

我们使用的是Angularjs 1x,我正试图在Angularjs过滤器中重构一些重复的代码,但我在正确处理问题上遇到了问题。应该很简单。

我们有一个使用Anonymous自执行函数的过滤器的标准结构,大致如下代码所示。我在for循环中有一些带有重复代码的if/else块,我想创建一个函数来消除这种重复,但是,我似乎无法正确调用该函数。我该怎么做?

(function() {
  //Named function
  function abc(Input){
    return function(value){
      for(var i=0; i<3; i++){
        if(w){
            //Duplicate code here
         } else if(x){
            //Duplicate code here
         } else if(y){
            //Duplicate code here
         } else if(z)
       }
     }
  }
}
))();

这里有一些类似于重复代码的东西,它在每个块中都是完全相同的重复代码。我们有处理标签的特殊服务。

if(Input[i].fpwInd === 'Y' && fpw.plan === 'State') {
    fpwValues.push(weblService.returnLabel("yes", $rootScope.label));
    break;
}else if(Input[i].fpwInd === 'N' && fpw.plan === 'Another State') {
    fpwValues.push(weblService.returnLabel("no", $rootScope.label));
    break;
}

这类似于工作的最终代码:

(function() {
  var fwp = function(input, plan){
    if(input == "value" && plan == "somevalue")
    fpwValues.push(weblService.returnLabel("yes", $rootScope.label));
    //rest of the if/else code here...
};  
  function abc(){
    return function(value){
      for(var i=0; i<3; i++){
        if(w){
            fwp(input, plan);
            break;
         } else if(x){
            fwp(input, plan);
            break;
         } else if(y){
            fwp(input, plan);
            break;
         } else if(z)
       }
     }
  }
}
))();

以第二个例子为基础,你能做这样的事情吗?

如果你能提供更多信息,那将是一个很大的帮助——为什么你不能正确地调用函数?你有什么错误吗?

(function() {
function getLabelStrForIndPlan(ind, plan) {
  if (ind === 'Y' && plan === 'State') {
    return 'yes';
  }
  else if (ind === 'N' && plan === 'Another State') {
    return 'no';
  }
}
function abc(Input){
  return function(value){
    for(var i=0; i<3; i++){
      var fpwInd = Input[i].fpwInd;
      var label = getLabelStrForIndPlan(fpwInd, fpw.plan);
      if (label) {
        fpwValues.push(weblService.returnLabel(label, $rootScope.label));
        break;
      }
    }
  }
}
})();