Created
July 18, 2016 03:01
-
-
Save javamonn/6b25ce51c9cdea8690ed3ae678888e2c 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
function flatten (arr) { | |
if (!Array.isArray(arr)) { | |
return arr | |
} | |
return arr.reduce((memo, elem) => { | |
if (Array.isArray(elem)) { | |
return memo.concat(flatten(elem)) | |
} else { | |
return memo.concat(elem) | |
} | |
}, []) | |
} | |
// tests | |
function isArrayEqual (arr1, arr2) { | |
if (!Array.isArray(arr1) || !Array.isArray(arr2)) { | |
return false | |
} | |
return arr1.length === arr2.length && arr1.every((elem, idx) => elem === arr2[idx]) | |
} | |
function assertEqual (arr1, arr2) { | |
var result = isArrayEqual(arr1, arr2) | |
console.assert(result, "assertEqual test failed") | |
return result | |
} | |
assertEqual(flatten([[1], 2, [3, 4, [5]]]), [1, 2, 3, 4, 5]) | |
assertEqual(flatten([[1,2,[3]],4]), [1, 2, 3, 4]) | |
assertEqual(flatten([1, [2, 3], [4]]), [1, 2, 3, 4]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment