Array method 系列之五 —— 数组扁平化:flatten && flattenDeep && flattenDepthflatten、flattenDeep、flattenDepth提供了将数组扁平化的思路。三者唯一的不同在于扁平数组的层次不同。flatten对数组进行一次扁平操作,flattenDeep扁平数组所有元素为一维为止。flattenDepth可以制定扁平数组的深度。
进行扁平化的核心代码是baseFlatten,其实现思路是递归。
源码如下:
// 判断数组元素是否可扁平化import isFlattenable from './isFlattenable.js' 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) { // 递归执行扁平函数,直至达到所要的结果
baseFlatten(value, depth - 1, predicate, isStrict, result)
} else {
result.push(...value)
}
} else if (!isStrict) {
result[result.length] = value
}
} return result
}比较flatten、flattenDeep、flattenDepth在执行baseFlatten的传参,即可看到差异。
// flattenfunction flatten(array) { const length = array == null ? 0 : array.length // depth = 1,执行一次扁平操作
return length ? baseFlatten(array, 1) : []
}// flattenDeepconst INFINITY = 1 / 0function flattenDeep(array) { const length = array == null ? 0 : array.length // 无限次执行扁平操作,直至所有元素都为一维。
return length ? baseFlatten(array, INFINITY) : []
}// flattenDepthfunction flattenDepth(array, depth) { const length = array == null ? 0 : array.length if (!length) { return []
} // 执行扁平数组操作次数为depth
depth = depth === undefined ? 1 : +depth return baseFlatten(array, depth)
}这里有个想法,在flattenDeep中传参判断,反倒没有源码写的简洁。
自己想了下,实现如下。
for (const value of array) { if (depth > 0 && predicate(value)) { if (deepEnd) { // 即flattenDeep执行这一步
baseFlatten(value, depth, predicate, isStrict, result, deepEnd)
} else if (depth > 1) {
baseFlatten(value, depth - 1, predicate, isStrict, result, deepEnd)
} else {
result.push(...value)
}
} else if (!isStrict) {
result[result.length] = value
}
}实在是没有源码简洁。
所以源码实现可以说是非常高明了。
作者:公子七
链接:https://www.jianshu.com/p/8eed7dc12f68