Polyfill Array.flat (#9917)

This commit is contained in:
Bram Kragten
2021-09-01 16:23:41 +02:00
committed by GitHub
parent 35a81e7f11
commit 0cbac8bb44
2 changed files with 27 additions and 0 deletions

View File

@@ -0,0 +1,26 @@
/* eslint-disable no-extend-native */
// @ts-expect-error
if (!Array.prototype.flat) {
Object.defineProperty(Array.prototype, "flat", {
configurable: true,
writable: true,
value: function (...args) {
const depth = typeof args[0] === "undefined" ? 1 : Number(args[0]) || 0;
const result = [];
const forEach = result.forEach;
const flatDeep = (arr: Array<any>, dpth: number) => {
forEach.call(arr, (val) => {
if (dpth > 0 && Array.isArray(val)) {
flatDeep(val, dpth - 1);
} else {
result.push(val);
}
});
};
flatDeep(this, depth);
return result;
},
});
}