Created
July 22, 2019 22:21
-
-
Save morganney/c075663349e688e418afad0cf7c5fa8f to your computer and use it in GitHub Desktop.
Flattens an array of integers with arbitrary nesting.
This file contains hidden or 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
// These are just here for unit testing | |
const assert = require('assert').strict | |
const expectedError = { | |
name: /^TypeError$/, | |
message: /not an array|only be integers/ | |
} | |
/** | |
* Flattens an array of arbitrarily nested integer arrays. | |
* | |
* @param {Array} list - Array of integers or nested integer arrays to any depth | |
* @return {Array} The argument flattened | |
* | |
* @example | |
* flatten([[1, 2, [3]], 4]) -> [1, 2, 3, 4] | |
*/ | |
const flatten = (list = []) => { | |
const flat = [] | |
if (!Array.isArray(list)) { | |
throw new TypeError('Passed argument was not an array.') | |
} | |
for (entry of list) { | |
if (Array.isArray(entry)) { | |
flat.push(...flatten(entry)) | |
continue | |
} | |
if (!Number.isInteger(entry)) { | |
throw new TypeError('Array items can only be integers or arrays of integers.') | |
} | |
flat.push(entry) | |
} | |
return flat | |
} | |
// Make some assertions | |
assert.deepEqual(flatten([[1, 2, [3]], 4]), [1, 2, 3, 4]) | |
assert.throws(flatten.bind(null, [1, 2, { foo: 'bar' }]), expectedError) | |
assert.throws(flatten.bind(null, { foo: 'bar' }), expectedError) | |
// Allow running from the CLI where arguments are passed as JSON strings | |
if (process.argv[2]) { | |
try { | |
console.log(flatten(JSON.parse(process.argv[2]))) | |
} catch (error) { | |
console.error(`Error: ${error.message}`) | |
process.exit(1) | |
} | |
} | |
// Allow requiring as a module | |
module.exports = flatten |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
node <path-to-script> "[[1, 2, [3]], 4]"
or