文为lodash源码分析的第16篇,后续会持续更新这个专题,欢迎指正。
依赖
import isFlattenable from './isFlattenable.js'
源码分析
baseFlatten函数的作用是将参数array扁平化。
function baseFlatten(array, depth, predicate, isStrict, result) {
predicate || (predicate = isFlattenable)
result || (result = [])
if (array == null) {
return result
}
for (const value of array) {
if (depth > 0 && predicate(value)) {
if (depth > 1) {
// Recursively flatten arrays (susceptible to call stack limits).
baseFlatten(value, depth - 1, predicate, isStrict, result)
} else {
result.push(...value)
}
} else if (!isStrict) {
result[result.length] = value
}
}
return result
}
首先,给形参predicate、result加上默认值。
其次,判断array是否为null、undefined,是则返回result。
接着,遍历array处理。
- 如果最大递归深度
depth大于0,且当前循环的值value可展开:- 判断递归深度
depth是否大于1: - 如果大于1,
depth-1继续递归; - 否则,将
value展开并添加到result里。
- 判断递归深度
- 否则,判断
isStrict是否为假值,是则将value添加到result里。
最后,返回result。