I am looking to iterate through an array of objects and call a method on them. If the result of that method meets certain conditions, I want to immediately return that result. The current implementation is as follows:
public getFirstMatch(value: string, allValues: string[]): Result {
let foundResult = undefined;
_.find(this.myArrayofMatchers, matcher => {
let result = matcher.isMatch(value, allValues);
if(result.isMatch){
foundResult = result;
return true;
}
})
return foundResult || new Result(false);
}
While this code works, it feels clunky and unclear. Using _.find
may not be the most intuitive choice, especially since the actual matcher
itself is not important. Additionally, the need for foundResult
variable seems unnecessary. Is there a more concise or efficient way to achieve this? Perhaps a different lodash function could help optimize this process?
As an alternative, I have also considered using a traditional for loop approach like below:
public isMatch(value: string, allValues: string[]): Result {
for (let i = 0; i < this.myArrayofMatchers.length; i++){
let result = this.myArrayofMatchers[i].isMatch(value, allValues);
if (result.isMatch) {
return result;
}
}
return new Result(false);
}