Array.flat原理实现

Array.flat实现

1
// input [1, 2, [3, 4, [5, 6, 7]], 8] -> output [1, 2, 3, 4, 5, 6, 7, 8];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
interface Array<T> {
flatInfinity(): T[];
flat(n?: number): T[];
}
Array.prototype.flatInfinity = function() {
const stack = [...this];
const value = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
value.push(next);
}
}
return value.reverse();
};
Array.prototype.flat = function(n = 1) {
return baseFlatten(this, n, []);
};
baseFlatternlodash.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 将数组拉平
* @param {Array} array 需要拉平数组
* @param {number} depth 数组的深度
* @param {Array} result 初始化将要返回的数组
* @returns {Array} 返回扁平后的数组
*/
function baseFlatten(array, depth, result) {
result || (result = []);
if (array == null) {
return result;
}
for (const value of array) {
if (depth > 0 && Array.isArray(value)) {
if (depth > 1) {
baseFlatten(value, depth - 1, result);
} else {
result.push(...value);
}
} else {
result[result.length] = value;
}
}
return result;
}