Last active
March 26, 2017 12:49
-
-
Save tomatau/9feead885f863699ec2f11e0d52ae9d5 to your computer and use it in GitHub Desktop.
Array Flatten
This file contains 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
const flatten = (source) => { | |
const length = source.length | |
let i = 0 | |
let flattened = [] | |
for (; i < length; i++) { | |
// recursive call could reach stack limit | |
flattened = flattened.concat( | |
!Array.isArray(source[i]) ? source[i] : flatten(source[i]) | |
) | |
// could iterate and expand first item in array until not an array | |
// then push onto flattened output | |
} | |
return flattened | |
} | |
console.assert( | |
arrayEqual( | |
flatten([ 1, 2, 3, 4 ]), | |
[ 1, 2, 3, 4 ] | |
), | |
`doesn't work with flat arrays` | |
) | |
console.assert( | |
arrayEqual( | |
flatten([ [ 1, 2, [ 3 ] ], 4 ]), | |
[ 1, 2, 3, 4 ] | |
), | |
`doesnt flatten simple nested arrays` | |
) | |
const deeplyNestedArray = Array.from({ length: 10000 }).reduce(acc => [ acc ], 0) | |
console.assert( | |
arrayEqual( | |
flatten(deeplyNestedArray), | |
[ 0 ] | |
), | |
`doesn't flatten deeply nested array` | |
) | |
function arrayEqual(arr1, arr2) { | |
const length = arr1.length | |
let i = 0 | |
if (length !== arr2.length) return false | |
for (; i < length; i++) | |
if (arr1[i] !== arr2[i]) | |
return false | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment