Created
January 1, 2019 16:15
Revisions
-
codenamezjames created this gist
Jan 1, 2019 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,28 @@ function flatten(arr, depth = Infinity, result = []) { if(!Array.isArray(arr)) return null for (const value of arr) { if (depth > 0 && Array.isArray(value)) { if (depth > 1) { flatten(value, depth - 1, result) } else { result.push(...value) } } else { result[result.length] = value } } return result } // Tests const superFlat = JSON.stringify(flatten( [[ [[[[1]]]], 2, [ 3 ] ], 4] )) === JSON.stringify([1, 2, 3, 4]) if ( !superFlat ) throw 'Failed to flatten many layers deep' const oneLayer = JSON.stringify(flatten( [1,2,3,[[4]]], 1 )) === JSON.stringify([1,2,3,[4]]) if (!oneLayer) throw 'Failed to only flatten one layer' const crazyInput = JSON.stringify(flatten( {1:1, 2:2, 3:3} )) === JSON.stringify(null) if(!crazyInput) throw 'Does not handle crazy inputs' console.log('Everything flattened successfully')