Last active
March 9, 2018 05:51
-
-
Save reyaz/8e2521aa406bd738388cf01b934d7da3 to your computer and use it in GitHub Desktop.
Code Sample: Array Flattener
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') | |
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
node flattener.js
shouldn’t output anything unless the assertion on line 3 fails.