Skip to content

Instantly share code, notes, and snippets.

@MarvinZ
Last active November 2, 2019 19:01
Show Gist options
  • Save MarvinZ/b00e6f220f437205e8a0800989a211d3 to your computer and use it in GitHub Desktop.
Save MarvinZ/b00e6f220f437205e8a0800989a211d3 to your computer and use it in GitHub Desktop.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Pre interview Test - Marvin Zumbado - marvinzzz@gmail.com</title>
<meta name="description" content="Pre interview Test">
<meta name="author" content="Marvinzzz@gmail.com">
</head>
<body>
<p>
This is just a test to flatten an array of arbitrarily nested arrays into a flat array of integers
</p>
<hr>
<input type=button onClick="doMagic()" value="Do Magic">
<hr>
<script>
function flattenME(a, r) {
if (!r) { r = [] }
for (var i = 0; i < a.length; i++) {
if (a[i].constructor == Array) {
r.concat(flattenME(a[i], r));
} else {
r.push(a[i]);
}
}
return r;
}
// test cases
const tests = [
{
input: [[1, 2, [3]], 4],
output: [1, 2, 3, 4]
},
{
input: [],
output: []
},
{
input: ['a', ['b', 'c', 'd']],
output: ['a', 'b', 'c', 'd']
},
{
input: [1, [2, [3, [4, 5, [6, 7], 8], 9], 10, 11], 12],
output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
}
]
function doMagic() {
alert('Please look at the console');
tests.forEach(({ input, output }) => {
console.log(flattenME(input));
console.log(output);
console.log(JSON.stringify(flattenME(input)) === JSON.stringify(output));
})
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment