Created
May 27, 2019 12:53
-
-
Save danse/44f3694904fa19241b7ee3231a03041f to your computer and use it in GitHub Desktop.
test for Theorem
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
/* | |
in order to run the tests install | |
https://github.com/davidchambers/doctest either globally or locally | |
and run `$ doctest theorem.js` | |
*/ | |
// > flatten([3]) | |
// [3] | |
// > flatten([1, 2, 3]) | |
// [1, 2, 3] | |
// > flatten([[[2], 3]]) | |
// [2, 3] | |
// > flatten([]) | |
// [] | |
// > flatten(NaN) | |
// NaN | |
// > flatten([[1, 2, [3]], 4]) | |
// [1, 2, 3, 4] | |
function flatten(nested) { | |
// propagate unhandled values | |
if (!Array.isArray(nested)) { | |
return nested; | |
} | |
// here we have an array | |
function callback(accum, current) { | |
if (Array.isArray(current)) { | |
return accum.concat(flatten(current)); | |
} else { | |
return accum.concat([current]); | |
} | |
} | |
return nested.reduce(callback, []); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment