Nathan
Nathan

Reputation: 6531

Lodash, call functions in a loop and return first matching result

I want to iterate through an array of objects, calling a method on them. If the result of that method meets some condition. I want to return that result immediately. I've written this:

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);
}

It works but it seems clunky and unclear. _.find, imho, isn't an clear indicator of what I'm trying to do as I don't care about the actual matcher. The fact foundResult needs to exist is something I find quite ugly. And it seems longer that it needs to be. Is there something I could do better here? Is there a better lodash function for this?

Incidentally, here's what I had in mind, using a for loop

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);
}

Upvotes: 0

Views: 360

Answers (1)

Piotr Białek
Piotr Białek

Reputation: 2709

You are using a _.find like a _.foreach. It's bad. Lodash find returns value, so you should take advantage of it.

Your method should look like this:

public getFirstMatch(value: string, allValues: string[]): Result {
    const foundResult = _.find(
        this.myArrayofMatchers,
        matcher => matcher.isMatch(value, allValues).isMatch
    );

    return foundResult || new Result(false);
}

Upvotes: 1

Related Questions