flattenDeepThenMap
Flattens all depths of a nested array and then maps each element using the provided iteratee function.
Behaves the same as arr.flat(Infinity).map(iteratee) while improving type issues.
Code
Benchmark
hz: Operations per secondmean: Average response time (ms)
| Name | hz | mean | Performance |
|---|---|---|---|
| modern-kit/flattenDeepThenMap | 1,587,624.53 | 0.0004 | fastest |
| lodash/flattenDeep.map | 1,222,383.95 | 0.0006 | - |
| js built-in/flat(Infinity).map | 330,750.78 | 0.0029 | slowest |
- modern-kit/flattenDeepThenMap
1.30xfaster than lodash/flattenDeep.map4.80xfaster than js built-in/flat(Infinity).map
Interface
typescript
/**
* @description A utility type that recursively unwraps nested array types to extract the innermost element type
*/
type ExtractNestedArrayType<T> = T extends readonly (infer U)[]
? ExtractNestedArrayType<U>
: T;
typescript
function flattenDeepThenMap<T, U>(
arr: T[] | readonly T[],
iteratee: (item: ExtractNestedArrayType<T>) => U
): U[];
Usage
typescript
import { flattenDeepThenMap } from '@modern-kit/utils';
const arr = [1, 2, [3, 4, [5, 6]]];
flattenDeepThenMap(arr, (item) => ({ id: item }));
// [{ id: 1}, { id: 2}, { id: 3}, { id: 4}, { id: 5}, { id: 6}];