Skip to content

Instantly share code, notes, and snippets.

@danse
Created May 27, 2019 12:53
Show Gist options
  • Save danse/44f3694904fa19241b7ee3231a03041f to your computer and use it in GitHub Desktop.
Save danse/44f3694904fa19241b7ee3231a03041f to your computer and use it in GitHub Desktop.
test for Theorem
/*
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