鲁迅说过:只有阅读过优秀库源码的人,才能配的上是真正的勇士。
flatten函数,主要功能在于减少一级array嵌套深度,通俗的来说就是把数组给打平,并且该函数面试的过程中出现频率很高,主要是考察递归的使用。
面试做法如下:
function flatten(array){
return array.reduce((cur,next)=>{
return cur.concat(Array.isArray(next)?flatten(next):next)
},[])
}
主要就是判断元素是否是数组,是的话就进行递归结构即可。
上述的做法只是凡人的一些做法,在lodash中的做法就比较骚气了,这也是我为什么要学习它的原因。lodash中引入打平层次的概念,换句话来说,我们是可以任意的指定打平的层级。
baseFlatten
/**
* The base implementation of `flatten` with support for restricting flattening.
*
* @private
* @param {Array} array The array to flatten.
* @param {number} depth The maximum recursion depth.
* @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
* @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
* @param {Array} [result=[]] The initial result value.
* @returns {Array} Returns the new flattened 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)) { // predicate判断当前元素是否是数组
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 // 做法很巧,利用数组的长度作为下标添加元素,也可以使用push方法
}
}
return result
}
export default baseFlatten