# findLast
# Description
从右往左找到第一个符合条件的值
# Params
(collection, predicate, fromIndex)
# Return
{*}
# Depend
import findLastIndex from './findLastIndex.js'
import isArrayLike from './isArrayLike.js'
# Code
function findLast(collection, predicate, fromIndex) {
let iteratee
const iterable = Object(collection)
if (!isArrayLike(collection)) {
collection = Object.keys(collection)
iteratee = predicate
predicate = (key) => iteratee(iterable[key], key, iterable)
}
const index = findLastIndex(collection, predicate, fromIndex)
return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined
}
# Analyze
- 定义了暂存对象
iterable - 判断了 传入的
collection是否为类数组,如果是则进行了predicate和iteratee的重新定义- 将
collection定义为Object.keys(collection) iteratee赋值为predicate,暂存predicate这里重新修改为(value, key, array)模式
- 将
- 使用
findLastIndex拿到最后一个符合的index - 如果
index不是 -1,则判断iteratee是否存在,如果存在表示collection为一个类数组, 则取collection[index], 否则取index
# Example
console.log(findLast({a:{v: 1},b:{v: 2},c:{v:3},d:{v:4}}, ({v}) => v < 3)) // { v: 2 }
console.log(findLast([1,2,3,4], (v) => v < 3)) // 2
← findKey findLastIndex →