Skip to content

Instantly share code, notes, and snippets.

@102
Last active July 20, 2016 07:08
Show Gist options
  • Save 102/20b6dddc4d3483c8edc659ffc1cfcd34 to your computer and use it in GitHub Desktop.
Save 102/20b6dddc4d3483c8edc659ffc1cfcd34 to your computer and use it in GitHub Desktop.
js array flatten
const assert = require('assert');
function flatten(array) {
// Return argument if it isn't an array
if (!Array.isArray(array)) {
return array;
}
const result = [];
// I should deep copy array here since function parameters should be immutable,
// but it's kind out of scope for this task
let nodes = array;
let node;
if (!nodes.length) {
return result;
}
node = nodes.pop();
do {
if (Array.isArray(node)) {
nodes.push.apply(nodes, node);
} else {
result.push(node);
}
} while (nodes.length && (node = nodes.pop()) !== undefined);
result.reverse();
return result;
}
[
{
actual: flatten([[1, 2, [3]], 4]),
expected: [1, 2, 3, 4]
},
{
actual: flatten([1, [2]]),
expected: [1, 2]
},
{
actual: flatten([1, 2, 3, 4]),
expected: [1, 2, 3, 4]
},
{
actual: flatten([[[[]]], [[]], []]),
expected: []
},
{
actual: flatten(null),
expected: null
},
{
actual: flatten(5),
expected: 5
}
].forEach(testCase => assert.deepEqual(testCase.actual, testCase.expected));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment