Skip to content

Instantly share code, notes, and snippets.

@sodik82
Created February 22, 2018 13:07
Show Gist options
  • Save sodik82/dc71eb9f488351edbbfa66bb58c2a8d8 to your computer and use it in GitHub Desktop.
Save sodik82/dc71eb9f488351edbbfa66bb58c2a8d8 to your computer and use it in GitHub Desktop.
Flattens nested arrays of numbers
/**
Flattens nested arrays of numbers
@param input (nested) array
@return deeply flattened array
*/
function flatten(input) {
function recursive(arr) {
if (Array.isArray(arr)) {
return arr.reduce((r, v) => r.concat(recursive(v)), [])
}
if (typeof arr === 'number') {
return [arr]
}
throw new Error('Flatten expects deep array of numbers')
}
if (!Array.isArray(input)) {
throw new Error('Flatten input must be array')
}
return recursive(input)
}
describe('flatten', () => {
const expectToThrow = run => {
expect(run).toThrow()
}
it('rejects undefined', () => {
expectToThrow(() => flatten(undefined))
})
it('flatten nested array', () => {
const result = flatten([[1, 2, [3]], 4])
expect(result).toEqual([1, 2, 3, 4])
})
it('rejects non-numbers', () => {
expectToThrow(() => flatten([1, ['a']]))
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment