Skip to content

Instantly share code, notes, and snippets.

@stalmok
Created February 11, 2019 01:34
Show Gist options
  • Save stalmok/26534cb38e2d36ff4fe9dd5be5d6d569 to your computer and use it in GitHub Desktop.
Save stalmok/26534cb38e2d36ff4fe9dd5be5d6d569 to your computer and use it in GitHub Desktop.
Flatten an array of arbitrarily nested arrays of integers into a flat array of integers
/**
* Code was written in Javascript (ES6)
* Tests will work only in Node.js environment
*/
/**
* Flatten an array of arbitrarily nested arrays of integers into
* a flat array of integers. e.g. [[1,2,[3]],4] -> [1,2,3,4].
*
* @param {Array} input
*/
function flatten(input) {
if (!Array.isArray(input)) {
throw TypeError(`An Array is expected, ${typeof input} was given.`);
}
let result = [];
input.forEach(element => {
result.push(...(Array.isArray(element) ? flatten(element) : [element]));
});
return result;
}
/** Tests */
const assert = require('assert');
assert.throws(() => flatten(), TypeError);
assert.throws(() => flatten(null), TypeError);
assert.throws(() => flatten(1), TypeError);
assert.throws(() => flatten('string'), TypeError);
assert.throws(() => flatten(false), TypeError);
assert.throws(() => flatten({}), TypeError);
assert.throws(() => flatten(NaN), TypeError);
assert.throws(() => flatten(Symbol()), TypeError);
assert.throws(() => flatten(() => {}), TypeError);
assert.deepEqual(flatten([]), []);
assert.deepEqual(flatten([1, 2, 3]), [1, 2, 3]);
assert.deepEqual(flatten([1, 2, [3]]), [1, 2, 3]);
assert.deepEqual(flatten([1, 2, [3, [4]]]), [1, 2, 3, 4]);
assert.deepEqual(flatten([[1, 2, [3]], 4]), [1, 2, 3, 4]);
assert.deepEqual(flatten([[1, 2, 3, 4]]), [1, 2, 3, 4]);
assert.deepEqual(flatten([[[[[1]]]]]), [1]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment