Last active
November 11, 2019 12:51
-
-
Save akullpp/84e87f20c3b257b40e0dcbf4f8cde1b3 to your computer and use it in GitHub Desktop.
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
export default xs => { | |
if (!Array.isArray(xs)) { | |
throw new ValidationError( | |
`Argument must be of Array-type, was ${typeof xs}`, | |
) | |
} | |
return flatten(xs) | |
} | |
class ValidationError extends Error { | |
constructor(message) { | |
this.message = message | |
} | |
} | |
const flatten = xs => | |
xs.reduce((acc, x) => acc.concat(Array.isArray(x) ? flatten(x) : x), []) |
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
import test from 'ava' | |
import flatten from './flatten' | |
const parameterized = (t, input, expected) => | |
t.deepEqual(flatten(input), expected) | |
parameterized.title = (providedTitle, input, expected) => | |
`${providedTitle} ${JSON.stringify(input)} to ${JSON.stringify(expected)}` | |
const throwing = (t, input) => t.throws(() => flatten(input)) | |
const valid = [ | |
[[], []], | |
[ | |
[1, 2, 3], | |
[1, 2, 3], | |
], | |
[ | |
[[1], [2], [3]], | |
[1, 2, 3], | |
], | |
[ | |
[[[1]], 2, 3], | |
[1, 2, 3], | |
], | |
] | |
valid.forEach(([input, expected]) => | |
test('Should flatten', parameterized, input, expected), | |
) | |
const invalid = [undefined, null, 1, 'foo', {}, () => {}] | |
invalid.forEach(input => | |
test(`Should not work for non-array types: ${input}`, throwing, input), | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment