Created
February 7, 2020 01:51
-
-
Save zardilior/8df6e334bb0646fc413b72e8fa4b8274 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 arrays with a recursive function | |
function flattenArray(array){ | |
let flattenedArray = [] | |
for(let element of array) { | |
if(Array.isArray(element)) { | |
flattenedArray.push(...flattenArray(element)) | |
} | |
else { | |
flattenedArray.push(element) | |
} | |
} | |
return flattenedArray | |
} | |
// unit testing | |
let tests = [ | |
{ | |
name: "Empty array", | |
parameter: [], | |
result: [], | |
}, { | |
name: "Flat array", | |
parameter: [1,2,3], | |
result:[1,2,3], | |
}, { | |
name: "Flat array", | |
parameter: [1,[2],3], | |
result:[1,2,3], | |
}, { | |
name: "Two levels array", | |
parameter: [1,2,3,[[3],2]], | |
result:[1,2,3,3,2], | |
}, { | |
name: "Very nested array", | |
parameter: [1,[2,[[3],[[[[]]]]]]], | |
result:[1,2,3], | |
} | |
] | |
for(let test of tests) { | |
const result = flattenArray(test.parameter) | |
if( compareArrays(result,test.result)) { | |
console.log(`${test.name} succeded`) | |
} | |
else { | |
console.log(`${test.name} failed with [${result}], expected [${test.result}]`) | |
console.log(result) | |
console.log(test.result) | |
} | |
} | |
// helper function | |
function compareArrays(array1, array2) { | |
for(let i in array1){ | |
if(array1[i]!==array2[i]) { | |
return false | |
} | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment