Skip to content

Instantly share code, notes, and snippets.

@reyaz
Last active March 9, 2018 05:51
Show Gist options
  • Save reyaz/8e2521aa406bd738388cf01b934d7da3 to your computer and use it in GitHub Desktop.
Save reyaz/8e2521aa406bd738388cf01b934d7da3 to your computer and use it in GitHub Desktop.
Code Sample: Array Flattener
const assert = require('assert')
assert.deepEqual(flatten([[1,2,[3]],4]), [1,2,3,4])
/**
* Returns a flattened array.
* @param {array} input
* @param {array=} output
*/
function flatten (input, output = []) {
input.forEach((element) => {
if (Array.isArray(element)) {
output.concat(flatten(element, output))
} else {
output.push(element)
}
})
return output
}
@reyaz
Copy link
Author

reyaz commented Mar 9, 2018

node flattener.js shouldn’t output anything unless the assertion on line 3 fails.

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