Skip to content

Commit

Permalink
feat(flattenDeep): add flattenDeep function (#160)
Browse files Browse the repository at this point in the history
  • Loading branch information
ssi02014 authored Jul 12, 2024
1 parent 34be6d7 commit ae69076
Show file tree
Hide file tree
Showing 10 changed files with 146 additions and 8 deletions.
27 changes: 27 additions & 0 deletions benchmarks/flattenDeep.bench.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { bench, describe } from 'vitest';
import { flattenDeep as flattenDeepToolkit } from 'es-toolkit';
import { flattenDeep as flattenDeepLodash } from 'lodash';

const createNestedArray = (values: number[]) => {
if (values.length === 0) {
return [];
}
const [first, ...rest] = values;
return [first, createNestedArray(rest)];
};

describe('flattenDeep', () => {
const arr = createNestedArray(Array.from({ length: 30 }, (_, index) => index));

bench('es-toolkit/flattenDeep', () => {
flattenDeepToolkit(arr);
});

bench('lodash/flattenDeep', () => {
flattenDeepLodash(arr);
});

bench('js built-in/flat(Infinity)', () => {
arr.flat(Infinity);
});
});
1 change: 1 addition & 0 deletions docs/.vitepress/en.mts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ function sidebar(): DefaultTheme.Sidebar {
{ text: 'fill', link: '/reference/array/fill' },
{ text: 'toFilled', link: '/reference/array/toFilled' },
{ text: 'flatten', link: '/reference/array/flatten' },
{ text: 'flattenDeep', link: '/reference/array/flattenDeep' },
{ text: 'forEachRight', link: '/reference/array/forEachRight' },
{ text: 'groupBy', link: '/reference/array/groupBy' },
{ text: 'intersection', link: '/reference/array/intersection' },
Expand Down
1 change: 1 addition & 0 deletions docs/.vitepress/ko.mts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ function sidebar(): DefaultTheme.Sidebar {
{ text: 'fill', link: '/ko/reference/array/fill' },
{ text: 'toFilled', link: '/ko/reference/array/toFilled' },
{ text: 'flatten', link: '/ko/reference/array/flatten' },
{ text: 'flattenDeep', link: '/ko/reference/array/flattenDeep' },
{ text: 'forEachRight', link: '/reference/array/forEachRight' },
{ text: 'groupBy', link: '/ko/reference/array/groupBy' },
{ text: 'intersection', link: '/ko/reference/array/intersection' },
Expand Down
8 changes: 4 additions & 4 deletions docs/ko/reference/array/flatten.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ function flatten<T, D extends number = 1>(arr: T[], depth?: D): Array<FlatArray<
## 예시

```typescript
const originArr = [1, [2, 3], [4, [5, 6]]];
const array = [1, [2, 3], [4, [5, 6]]];

const array1 = flatten(originArr);
const result1 = flatten(array);
// [1, 2, 3, 4, [5, 6]]를 반환해요.

const array2 = flatten(originArr, 1);
const result2 = flatten(array, 1);
// [1, 2, 3, 4, [5, 6]]를 반환해요.

const array3 = flatten(originArr, 2);
const result3 = flatten(array, 2);
// [1, 2, 3, 4, 5, 6]를 반환해요.
```
31 changes: 31 additions & 0 deletions docs/ko/reference/array/flattenDeep.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# flattenDeep

중첩된 배열의 모든 깊이를 풀어서 평탄화해요.

JavaScript 언어에 포함된 [Array#flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat)`flat(Infinity)`로 호출했을 때와 동일하게 동작하지만, 더 빨라요.

## 인터페이스

```typescript
// 중첩된 배열을 재귀적으로 풀어내어 가장 내부의 요소 타입을 추출하는 유틸리티 타입이에요.
type ExtractNestedArrayType<T> = T extends ReadonlyArray<infer U> ? ExtractNestedArrayType<U> : T;

function flattenDeep<T>(arr: T[]): Array<ExtractNestedArrayType<T>>;
```

### 파라미터

- `arr` (`T[]`): 평탄화할 중첩 배열이에요.

### 반환 값

(`Array<ExtractNestedArrayType<T>>`): 모든 깊이가 평탄해진 새로운 배열이에요.

## 예시

```typescript
const array = [1, [2, [3]], [4, [5, 6]]];

const result = flattenDeep(array);
// [1, 2, 3, 4, 5, 6]를 반환해요.
```
8 changes: 4 additions & 4 deletions docs/reference/array/flatten.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ function flatten<T, D extends number = 1>(arr: T[], depth?: D): Array<FlatArray<
## Examples

```typescript
const originArr = [1, [2, 3], [4, [5, 6]]];
const array = [1, [2, 3], [4, [5, 6]]];

const array1 = flatten(originArr);
const result1 = flatten(array);
// Return [1, 2, 3, 4, [5, 6]]

const array2 = flatten(originArr, 1);
const result2 = flatten(array, 1);
// Return [1, 2, 3, 4, [5, 6]]

const array3 = flatten(originArr, 2);
const result3 = flatten(array, 2);
// Return [1, 2, 3, 4, 5, 6]
```
31 changes: 31 additions & 0 deletions docs/reference/array/flattenDeep.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# flattenDeep

Flattens all depths of a nested array.

It works the same as if you called [Array#flat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat) as `flat(Infinity)` in the JavaScript language, but it's faster.

## Signature

```typescript
// Utility type for recursively unpacking nested array types to extract the type of the innermost element
type ExtractNestedArrayType<T> = T extends ReadonlyArray<infer U> ? ExtractNestedArrayType<U> : T;

function flattenDeep<T>(arr: T[]): Array<ExtractNestedArrayType<T>>;
```

### Parameters

- `arr` (`T[]`): The array to flatten.

### Returns

(`Array<ExtractNestedArrayType<T>>`): A new array with all depths flattened.

## Examples

```typescript
const array = [1, [2, [3]], [4, [5, 6]]];

const result = flattenDeep(array);
// Return [1, 2, 3, 4, 5, 6]
```
18 changes: 18 additions & 0 deletions src/array/flattenDeep.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { describe, expect, it } from 'vitest';
import { flattenDeep } from './flattenDeep';

describe('flattenDeep', () => {
it('should flatten a deeply nested array of numbers', () => {
const originArr = [1, [2, [3, [4, [5]]]]];
const expectedArr = [1, 2, 3, 4, 5];

expect(flattenDeep(originArr)).toEqual(expectedArr);
});

it('should flatten a deeply nested array with mixed types', () => {
const originArr = [1, ['str', [3, [4, [false, [{ id: 1 }]]]]]];
const expectedArr = [1, 'str', 3, 4, false, { id: 1 }];

expect(flattenDeep(originArr)).toEqual(expectedArr);
});
});
28 changes: 28 additions & 0 deletions src/array/flattenDeep.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { flatten } from './flatten';

/**
* Utility type for recursively unpacking nested array types to extract the type of the innermost element
*
* @example
* ExtractNestedArrayType<(number | (number | number[])[])[]>
* // number
*
* ExtractNestedArrayType<(boolean | (string | number[])[])[]>
* // string | number | boolean
*/
type ExtractNestedArrayType<T> = T extends ReadonlyArray<infer U> ? ExtractNestedArrayType<U> : T;

/**
* Flattens all depths of a nested array.
*
* @template T - The type of elements within the array.
* @param {T[]} arr - The array to flatten.
* @returns {Array<ExtractNestedArrayType<T>>} A new array that has been flattened.
*
* @example
* const arr = flattenDeep([1, [2, [3]], [4, [5, 6]]]);
* // Returns: [1, 2, 3, 4, 5, 6]
*/
export function flattenDeep<T>(arr: readonly T[]): Array<ExtractNestedArrayType<T>> {
return flatten(arr, Infinity) as Array<ExtractNestedArrayType<T>>;
}
1 change: 1 addition & 0 deletions src/array/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export { dropRightWhile } from './dropRightWhile.ts';
export { dropWhile } from './dropWhile.ts';
export { fill } from './fill.ts';
export { flatten } from './flatten.ts';
export { flattenDeep } from './flattenDeep.ts';
export { forEachRight } from './forEachRight.ts';
export { groupBy } from './groupBy.ts';
export { intersection } from './intersection.ts';
Expand Down

0 comments on commit ae69076

Please sign in to comment.