Created
February 22, 2018 13:07
-
-
Save sodik82/dc71eb9f488351edbbfa66bb58c2a8d8 to your computer and use it in GitHub Desktop.
Flattens nested arrays of numbers
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
/** | |
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