Skip to content

Instantly share code, notes, and snippets.

@jiverson
Created August 15, 2019 17:30
Show Gist options
  • Save jiverson/ef566debd9b277ab5fedc7c7f21949a3 to your computer and use it in GitHub Desktop.
Save jiverson/ef566debd9b277ab5fedc7c7f21949a3 to your computer and use it in GitHub Desktop.
// 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