Skip to content

Instantly share code, notes, and snippets.

@Stradivario
Created April 2, 2020 09:31
Show Gist options
  • Save Stradivario/16b17c23592b583040ab457ae2922b9f to your computer and use it in GitHub Desktop.
Save Stradivario/16b17c23592b583040ab457ae2922b9f to your computer and use it in GitHub Desktop.
Flatten array typescript
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