Skip to content

Instantly share code, notes, and snippets.

Created October 2, 2019 18:48
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save MariusAlch/b54e17994bb814e401c174a30bb1dd01 to your computer and use it in GitHub Desktop.
const assert = require("assert");
* Write some code, that will 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].
function flattenArray(array) {
if (!Array.isArray(array)) {
throw new Error("Array expected");
return array.reduce(
(accumulator, element) =>
accumulator.concat(Array.isArray(element) ? flattenArray(element) : element),
assert.deepStrictEqual(flattenArray([[1,2,[3]],4]), [1,2,3,4], "Should flatten any nested array");
assert.deepStrictEqual(flattenArray([1,2,3,4]), [1,2,3,4], "Should not flatten if not needed");
assert.deepStrictEqual(flattenArray([]), [], "Should flatten empty array");
assert.deepStrictEqual(flattenArray([[]]), [], "Should flatten nested empty arrays");
const errorValues = [
null, undefined, {}, 1, "string", Date()
errorValues.forEach(errorValue => {
assert.throws(() => flattenArray(errorValue), 'Should throw an error when not an array is provided')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment