Created
April 2, 2020 09:31
-
-
Save Stradivario/16b17c23592b583040ab457ae2922b9f to your computer and use it in GitHub Desktop.
Flatten array typescript
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 function flatten<T>(array: T[], depth?: number): Generator<T>; | |
export function flatten<T>(array: T[][], depth?: number): Generator<T>; | |
export function flatten<T>(array: T[][][], depth?: number): Generator<T>; | |
export function flatten<T>(array: T[][][][], depth?: number): Generator<T>; | |
export function flatten<T>(array: T[][][][][], depth?: number): Generator<T>; | |
export function flatten<T>(array: T[][][][][][][], depth?: number): Generator<T>; | |
export function flatten<T>(array: T[][][][][][][][], depth?: number): Generator<T>; | |
export function flatten<T>(array: T[][][][][][][][][], depth?: number): Generator<T>; | |
export function flatten<T>(array: T[][][][][][][][][][], depth?: number): Generator<T>; | |
export function flatten<T>(array: T[][][][][][][][][][][], depth?: number): Generator<T>; | |
export function* flatten<T>(array: T[], depth = Infinity): Generator<T> { | |
if (depth === undefined) { | |
depth = 1; | |
} | |
for (const item of array) { | |
if (Array.isArray(item) && depth > 0) { | |
yield* flatten(item, depth - 1); | |
} else { | |
yield item; | |
} | |
} | |
} | |
export function flattenToArray<T>(array: T[]) { | |
return [...flatten(array)]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment