Created
October 2, 2019 18:48
-
-
Save MariusAlch/b54e17994bb814e401c174a30bb1dd01 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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