Created
December 8, 2021 18:42
-
-
Save DemonDaddy22/1d6e853c0f816d32e886540bdbd3cb11 to your computer and use it in GitHub Desktop.
Polyfilling in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Array Polyfill to flatten out an array upto specified depth | |
* | |
* @param {number} depth | |
* @default 1 | |
* @returns new flattened out array object | |
* | |
* @example `[1, 2, [3, 4, [5, 6, [7]]]].flatten() -> [1, 2, 3, 4, [5, 6, [7]]]` | |
* @example `[1, 2, [3, 4, [5, 6, [7]]]].flatten(2) -> [1, 2, 3, 4, 5, 6, [7]]` | |
* | |
*/ | |
Array.prototype.flatten = function (depth = 1) { | |
if (typeof depth !== 'number') { | |
throw new TypeError('depth must be a number'); | |
} | |
return depth <= 0 | |
? this.slice() | |
: this.reduce((accu, curr) => ( | |
accu.concat(Array.isArray(curr) ? curr.flatten(depth - 1) : curr) | |
), []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment