Skip to content

Instantly share code, notes, and snippets.

@sdebaun
Created January 10, 2019 08:33
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sdebaun/04c41a881d132f417cc1c8801be63a94 to your computer and use it in GitHub Desktop.
using jest, ts-jest
const flatten = (arr: Array<any>): Array<any> =>
arr.reduce((a, x) => a.concat(flattenOrArray(x)), [])
const flattenOrArray = (x: any) =>
Array.isArray(x) ? flatten(x) : [x]
test('no nesting', () => {
expect(flatten([1, 2, 3])).toEqual([1, 2, 3])
})
test('1 level', () => {
expect(flatten([[1, 2], 3])).toEqual([1, 2, 3])
})
test('3 level', () => {
expect(flatten([[1, 2], 3, [4, [5, 6]]])).toEqual([1, 2, 3, 4, 5, 6])
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment