Skip to content

Instantly share code, notes, and snippets.

@akullpp
Last active November 11, 2019 12:51
Show Gist options
  • Save akullpp/84e87f20c3b257b40e0dcbf4f8cde1b3 to your computer and use it in GitHub Desktop.
Save akullpp/84e87f20c3b257b40e0dcbf4f8cde1b3 to your computer and use it in GitHub Desktop.
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), [])
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