Reputation: 15703
We are using Angularjs 1x and I'm trying to refactor some duplicate code in an Angularjs filter, but I'm having problems getting it right. Should be very simple.
We have a standard structure for using filters using an Anonymous self-executing function, something along the lines of the code below. I have some if/else blocks with duplicate code in a for loop and I wanted to create a function that would eliminate that duplication, however, I can't seem to call the function properly. How would I go about doing this?
(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)
}
}
}
}
))();
Here is something similar to the duplicate code and it's the exact same duplicate code in each block. We have a special service to handle labels.
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;
}
This is something like the final code that worked:
(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)
}
}
}
}
))();
Upvotes: 0
Views: 182
Reputation: 1240
Taking your second example as the basis could you do something like this?
If you could give more info though it would be a great help - why can't you call the function properly? are you getting any errors?
(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;
}
}
}
}
})();
Upvotes: 1