Created
January 1, 2019 16:15
-
-
Save codenamezjames/cd60f59adb1717b7122a61624f33bc10 to your computer and use it in GitHub Desktop.
Javascript flatten similar to ruby's flatten
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
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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment