Skip to content

Instantly share code, notes, and snippets.

@DemonDaddy22
Created December 8, 2021 18:42
Show Gist options
  • Save DemonDaddy22/1d6e853c0f816d32e886540bdbd3cb11 to your computer and use it in GitHub Desktop.
Save DemonDaddy22/1d6e853c0f816d32e886540bdbd3cb11 to your computer and use it in GitHub Desktop.
Polyfilling in JavaScript
/**
* 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