2016-09-17 51 views
0

我想遍歷一個對象數組,調用它們的方法。如果該方法的結果符合某些條件。我想立即返回結果。我寫了這個:Lodash,在循環中調用函數並返回第一個匹配結果

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

它的作品,但它似乎笨重和不清楚。 _.find,恕我直言,不是我想要做的事情的明確指標,因爲我不關心實際的matcherfoundResult需要存在的事實是我覺得很難看。而且它似乎需要更長時間。 有什麼我可以在這裏做得更好?有更好的lodash功能嗎?

順便說一句,這是我腦子裏想的,使用for循環

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

不'爲(_myArrray的VAR匹配)'工作? – georg

+0

@georg你的意思是foreach?我聽說使用lodash是更好的練習,我關心效率(我知道,愚蠢的語言選擇)。 'for(let i = 0; i

+1

不,我的意思是'for..of'循環,其功能與您的第二個片段完全相同。如果一個普通的語言結構起作用,則不需要使用庫。 – georg

回答

1

您使用的是_.find_.foreach。這不好。 Lodash找到回報值,所以你應該利用它。

你的方法應該是這樣的:

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

    return foundResult || new Result(false); 
} 
相關問題