Skip to content

Instantly share code, notes, and snippets.

@stalmok stalmok/flatten.js

Created Feb 11, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.