初探 Iterator.find()
前言
在之前的 初探 Iterator.every()介紹 Iterator.every() ,這次學習 Iterator.find() ,在此把學習的過程做個紀錄。
內容
範例如下
function* count(){
let curNum = 0;
while(true){
console.log( curNum );
yield curNum++;
}
}
//
const isBigEqualThree = ( num ) => num >= 3 ;
let conItor = count();
console.log( conItor.find(isBigEqualThree) );
// 0
// 1
// 2
// 3
// 3
//
console.log( count().take(2).find( isBigEqualThree ) );
// 0
// 1
// undefined
//
console.log( count().take(5).find( isBigEqualThree ) );
// 0
// 1
// 2
// 3
// 3
Iterator.find() 的用法與 Iterator.every() 非常相像,都要給一個 Function 後執行,差異是 Iterator.find() 的 Function 是 False 後持續下一個 yield ,而 Iterator.every() 則是 True 後持續下一個 yield ,還有一個差異是回傳的結果, Iterator.find() 的回傳結果是 Function 回傳 True 時的 yield 的結果,而 Iterator.every() 的回傳結果是 Function 是否回傳過 False。範例跟 Iterator.every() 的很像,方便跟之前的範例比較,條件改成大於等於 3 ,這次一樣會在 count() 每次 yield 前顯示結果,幫便了解到底跑了多少次 count(),範例第一次 Iterator.find() 執行到 3 ,也就是條件為 True 的時候,而最後回傳值就是條件為 True 的 yield ,也就 3 ,範例接著搭配 Iterator.take() 來使用,注意因為 Iterator.take() 只到 2 ,Iterator.find() 從未跑到 Function 回傳 True 的狀況,這個時候的回傳值會是 undefiend ! 最後範例把 Iterator.take() 調到 5 ,這是就會跑到 Function 回傳 True 的狀況,所以回傳依舊是 3 。
參考資料
[ developer.mozilla.org ] Iterator.prototype.find()