Created
August 15, 2019 17:30
-
-
Save jiverson/ef566debd9b277ab5fedc7c7f21949a3 to your computer and use it in GitHub Desktop.
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
// input [[1,2,[3]],4] -> [1,2,3,4] | |
/** | |
* Assumptions | |
* 1. We don't need to take care of duplicates. | |
* 2. Arrays are only interger values. | |
* 3. No null or undefined values allowed. | |
*/ | |
function run(input) { | |
const flatten = (arr) => arr.reduce((acc, item) => { | |
if (Array.isArray(item) && item.length > 0) { | |
acc = acc.concat(flatten(item)); | |
} else { | |
acc.push(item); | |
} | |
return acc; | |
}, []); | |
return flatten(input); | |
} | |
function equals(actual, expected) { | |
const a = JSON.stringify(actual); | |
const b = JSON.stringify(expected); | |
console.log(a, b); | |
return a === b; | |
} | |
let actual; | |
actual = run([1,2,[3],4]); | |
console.log(equals(actual, [1, 2, 3, 4])); | |
actual = run([[1,2,[3]],4]); | |
console.log(equals(actual, [1, 2, 3, 4])); | |
actual = run([[1,2,[3]],[4]]); | |
console.log(equals(actual, [1, 2, 3, 4])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment