Skip to content

Instantly share code, notes, and snippets.

@morganney
Created July 22, 2019 22:21
Show Gist options
  • Save morganney/c075663349e688e418afad0cf7c5fa8f to your computer and use it in GitHub Desktop.
Save morganney/c075663349e688e418afad0cf7c5fa8f to your computer and use it in GitHub Desktop.
Flattens an array of integers with arbitrary nesting.
// 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
@morganney
Copy link
Author

node <path-to-script> "[[1, 2, [3]], 4]"

or

const flatten = require('path-to-module')

flatten([[1, 2, [3]], 4])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment