Created
October 30, 2019 13:10
-
-
Save MrfksIv/603b002d72a50498d02cb01c0972b075 to your computer and use it in GitHub Desktop.
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
/* | |
* The function flattens an arbitrarily nested array of k-dimensions using recursion. | |
* The implementation is quite fast (i.e. O(n) where n is the total number of | |
* elements in the k-th dimensional array where k >= 1). | |
* However stack overflow errors could occur in cases where k is particularly large - | |
* thus requiring a very deep level of recursion. | |
* | |
* @param {number[][]} - A k-dimensional array where k >= 1 | |
* @returns {number[]} - A 1-dimensional flattened array | |
*/ | |
const flatten = function(arr) { | |
if (!Array.isArray(arr)) { | |
throw new TypeError('Argument is not an array'); | |
} | |
// a closure and an IIFE is used to 'cache' the partly flattened array until completion | |
// of the recursively called innerFlatten() | |
const flattenedArray = []; | |
return (function innerFlatten(arr) { | |
for (let i = 0, length = arr.length; i < length; i++) { | |
const value = arr[i]; | |
if (Array.isArray(value)) { | |
innerFlatten(value); | |
} else { | |
flattenedArray.push(value); | |
} | |
} | |
return flattenedArray; | |
})(arr); | |
}; | |
module.exports = flatten; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment