Home > Back-end >  Would like to stop execution of code when a match is met
Would like to stop execution of code when a match is met

Time:02-21

I created this service method in Angular JS which checks if an array of potential statuses(pendingApplications) match any of an array of set statuses(applicableStatuses). For this to work it meetsStatusCondition should return true after the first match occurs. Only 1 of the numbers in pendingApplications array needs to match and I'd like to end the execution of this function. Currently it's looping through every item in pendingApplications array

    `containsApplicableStatus: function(pendingApplications, applicableStatuses) {
        pendingApplications.forEach(function(status) {
            if (applicableStatuses.includes(status)) {
                return pendingApplications.meetsStatusCondition = true;
            }
        });
    }`

CodePudding user response:

This is a limitation with .forEach, you can't break out if it like you can with a for loop

Just a regular for loop will work

for (const status of applicableStatuses){
if (applicableStatuses.includes(status)) { 
pendingApplications.meetsStatusCondition = true; 
break //or return if you want to exit out of the enclosing function instead of just the loop
} 
}

CodePudding user response:

Often when you want to short-circuit a forEach like this, what you're really looking for is another method like find() or some().

containsApplicableStatus: function(pendingApplications, applicableStatuses) {
    pendingApplications.meetsStatusCondition = pendingApplications.some(function(status) {
        return applicableStatuses.includes(status)
    });
}

CodePudding user response:

There is no point in using forEach (which doesn't have a breaking option) if you could just use a regular for ... of loop instead:

containsApplicableStatus: function(pendingApplications, applicableStatuses) {
  for (const status of pendingApplications) {
    if (applicableStatuses.includes(status)) {
      pendingApplications.meetsStatusCondition = true;
      break;
    }
  }
}

However, even this seems a bit too complicated, you could just set meetsStatusCondition to the result of some:

containsApplicableStatus: function(pendingApplications, applicableStatuses) {
  pendingApplications.meetsStatusCondition =
    pendingApplications.some(status => applicableStatues.includes(status));
}

I do wonder if it makes sense to set a non-index property on your array though, maybe rethink that. This works but it's usually not something you'd expect on an array, and it will be lost if you convert that array to JSON for instance.

  • Related