|
| 1 | +# reduceAsync |
| 2 | + |
| 3 | +非同期リデューサー関数を使用して配列を単一の値に縮約します。 |
| 4 | + |
| 5 | +```typescript |
| 6 | +const result = await reduceAsync(array, reducer, initialValue); |
| 7 | +``` |
| 8 | + |
| 9 | +## 参照 |
| 10 | + |
| 11 | +### `reduceAsync(array, reducer, initialValue)` |
| 12 | + |
| 13 | +各要素を順次処理して配列を1つの値に縮約する場合は、`reduceAsync`を使用してください。リデューサー関数は左から右へ各要素に順次適用され、前の呼び出しの累積結果を次の呼び出しに渡します。 |
| 14 | + |
| 15 | +```typescript |
| 16 | +import { reduceAsync } from 'es-toolkit/array'; |
| 17 | + |
| 18 | +// 各数値の非同期値を取得して合計します。 |
| 19 | +const numbers = [1, 2, 3, 4, 5]; |
| 20 | +const sum = await reduceAsync(numbers, async (acc, n) => acc + (await fetchValue(n)), 0); |
| 21 | +// 返り値:すべての取得値の合計 |
| 22 | + |
| 23 | +// 配列をオブジェクトに変換します。 |
| 24 | +const users = [{ id: 1 }, { id: 2 }, { id: 3 }]; |
| 25 | +const userMap = await reduceAsync( |
| 26 | + users, |
| 27 | + async (acc, user) => { |
| 28 | + const details = await fetchUserDetails(user.id); |
| 29 | + acc[user.id] = details; |
| 30 | + return acc; |
| 31 | + }, |
| 32 | + {} as Record<number, any> |
| 33 | +); |
| 34 | +// 返り値:{ 1: {...}, 2: {...}, 3: {...} } |
| 35 | +``` |
| 36 | + |
| 37 | +他の非同期配列メソッドとは異なり、`reduceAsync`は各要素を順次処理する必要があるため、並行実行をサポートしていません。前のステップの結果が次のステップに必要だからです。 |
| 38 | + |
| 39 | +#### パラメータ |
| 40 | + |
| 41 | +- `array` (`readonly T[]`):縮約する配列です。 |
| 42 | +- `reducer` (`(accumulator: U, currentValue: T, currentIndex: number, array: readonly T[]) => Promise<U>`):各要素を処理する非同期関数です。累積値と現在の値を受け取り、新しい累積値を返します。 |
| 43 | +- `initialValue` (`U`):アキュムレーターの初期値です。 |
| 44 | + |
| 45 | +#### 戻り値 |
| 46 | + |
| 47 | +(`Promise<U>`):最終的な累積値のPromiseを返します。 |
| 48 | + |
| 49 | +--- |
| 50 | + |
| 51 | +### `reduceAsync(array, reducer)` |
| 52 | + |
| 53 | +初期値なしで配列を縮約する場合、最初の要素が初期値として使用され、2番目の要素からリデューサー関数が適用されます。 |
| 54 | + |
| 55 | +```typescript |
| 56 | +import { reduceAsync } from 'es-toolkit/array'; |
| 57 | + |
| 58 | +// 初期値なしで合計を計算します。 |
| 59 | +const numbers = [1, 2, 3, 4, 5]; |
| 60 | +const sum = await reduceAsync(numbers, async (acc, n) => acc + n); |
| 61 | +// 返り値:15 (1 + 2 + 3 + 4 + 5) |
| 62 | + |
| 63 | +// 空の配列はundefinedを返します。 |
| 64 | +const emptyArray: number[] = []; |
| 65 | +const result = await reduceAsync(emptyArray, async (acc, n) => acc + n); |
| 66 | +// 返り値:undefined |
| 67 | +``` |
| 68 | + |
| 69 | +初期値なしで空の配列に対して`reduceAsync`を呼び出すと、`undefined`を返します。 |
| 70 | + |
| 71 | +#### パラメータ |
| 72 | + |
| 73 | +- `array` (`readonly T[]`):縮約する配列です。 |
| 74 | +- `reducer` (`(accumulator: T, currentValue: T, currentIndex: number, array: readonly T[]) => Promise<T>`):各要素を処理する非同期関数です。累積値と現在の値を受け取り、新しい累積値を返します。 |
| 75 | + |
| 76 | +#### 戻り値 |
| 77 | + |
| 78 | +(`Promise<T | undefined>`):最終的な累積値のPromiseを返します。配列が空の場合は`undefined`を返します。 |
0 commit comments