Last active
July 3, 2017 23:50
-
-
Save powerslacker/7ff6475d739de426794ce1cac3b935df to your computer and use it in GitHub Desktop.
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
// flatten an array of arbitrarily nested arrays of integers into a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4] | |
function flatten (arr) { | |
let result = arr | |
// check if arr contains an array | |
while(result.find(item => Array.isArray(item))) { | |
// merge arr w/ top level arr | |
result = [].concat.apply([], result) | |
} | |
// when complete return flattened arr | |
return result | |
} | |
function testFlatten () { | |
let assertions = [ | |
{ | |
input: [ [1,2,[3, [4, 5]]], 6], | |
output: [1,2,3,4,5,6], | |
desc: 'test 3 level array' | |
}, | |
{ | |
input: [[1,2,[3]],4], | |
output: [1,2,3,4], | |
desc: 'test 2 level array' | |
}, | |
] | |
assertions.forEach(assertion => { | |
if (!testArrayEquality(flatten(assertion.input), assertion.output)) { | |
console.warn(`Test failed - ${assertion.desc}`) | |
} | |
else { | |
console.log(`Test passed - ${assertion.desc}`) | |
} | |
}) | |
} | |
function testArrayEquality (src, comparison) { | |
return src.length === comparison.length && src.every((item, index) => { | |
return item === comparison[index]; | |
}) | |
} | |
testFlatten() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment