Last active
August 17, 2021 15:56
-
-
Save BalasubramaniM/24e676fdd3f858fb27be7d43253be07b to your computer and use it in GitHub Desktop.
Array Flat Polyfill with Depth Implementation
This file contains hidden or 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.prototype.myFlat = function (depth) { | |
function getFlattenedArr(arr) { | |
let res = []; | |
let isSpreaded = false; | |
for (let value of arr) { | |
if (Array.isArray(value)) { | |
isSpreaded = true; | |
res.push(...value); | |
} else { | |
res.push(value); | |
} | |
} | |
return { | |
res, | |
isSpreaded, | |
}; | |
} | |
let result = [...this]; | |
let counter = 0; | |
while (counter < depth) { | |
const { res, isSpreaded } = getFlattenedArr(result); | |
result = res; | |
counter++; | |
if (!isSpreaded) break; | |
} | |
return result; | |
}; | |
const arr = [[1, 2, 3], 4, [5, [6]], 7]; | |
console.log(arr.myFlat(Infinity)); // [1,2,3,4,5,6,7]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment