From 8a9ccb0d159ba4f2ceff6e187f8205dcc76d369e Mon Sep 17 00:00:00 2001 From: Masahiro FUJIMOTO Date: Sat, 18 Sep 2021 22:52:17 +0900 Subject: Global_Objects/Array/reduceRight を更新 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Markdown化 - 2021/07/21 時点の英語版に同期 --- .../global_objects/array/reduceright/index.md | 466 +++++++++++---------- 1 file changed, 242 insertions(+), 224 deletions(-) diff --git a/files/ja/web/javascript/reference/global_objects/array/reduceright/index.md b/files/ja/web/javascript/reference/global_objects/array/reduceright/index.md index 4d1055ccab..04be78ad80 100644 --- a/files/ja/web/javascript/reference/global_objects/array/reduceright/index.md +++ b/files/ja/web/javascript/reference/global_objects/array/reduceright/index.md @@ -5,192 +5,227 @@ tags: - Array - ECMAScript 5 - JavaScript - - Method - - Prototype - - polyfill + - メソッド + - プロトタイプ + - ポリフィル +browser-compat: javascript.builtins.Array.reduceRight translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight --- -
{{JSRef}}
+{{JSRef}} -

reduceRight() メソッドは、隣り合う 2 つの配列要素に対して (右から左へ) 関数を適用して、単一の値にします。

+**`reduceRight()`** メソッドは、アキュームレーターと配列のそれぞれの値に対して (右から左へ) 関数を適用して、単一の値にします。 -
{{EmbedInteractiveExample("pages/js/array-reduce-right.html","shorter")}}
+{{EmbedInteractiveExample("pages/js/array-reduce-right.html","shorter")}} - +左から右へ適用する際は {{jsxref("Array.prototype.reduce()")}} を参照してください。 -

左から右へ適用する際は {{jsxref("Array.prototype.reduce()")}} を参照してください。

+## 構文 -

構文

+```js +// アロー関数 +reduceRight((accumulator, currentValue) => { ... } ) +reduceRight((accumulator, currentValue, index) => { ... } ) +reduceRight((accumulator, currentValue, index, array) => { ... } ) +reduceRight((accumulator, currentValue, index, array) => { ... }, initialValue) -
arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])
+// コールバック関数 +reduceRight(callbackFn) +reduceRight(callbackFn, initialValue) -

引数

+// コールバック畳み込み関数 +reduceRight(function callbackFn(accumulator, currentValue) { ... }) +reduceRight(function callbackFn(accumulator, currentValue, index) { ... }) +reduceRight(function callbackFn(accumulator, currentValue, index, array){ ... }) +reduceRight(function callbackFn(accumulator, currentValue, index, array) { ... }, initialValue) +``` -
-
callback
-
4 つの引数を取って、配列内の各値に対し実行するコールバック関数 -
-
accumulator
-
現在処理されている配列要素の 1 つ前の要素。もしくは、指定されていれば initialValue。(下記参照)
-
currentValue
-
現在処理されている配列要素
-
index{{optional_inline}}
-
現在処理されている配列要素のインデックス
-
array{{optional_inline}}
-
reduceRight() によって呼ばれる配列
-
-
-
initialValue {{optional_inline}}
-
callback の最初の呼び出しのときに、最初の実引数として用いるためのオブジェクト。initialValue が渡されなかった際は、配列の最後の要素が適用されます。また、空の配列に対して、初期値なしで呼び出すと TypeError になります。
-
+### 引数 -

返値

+- `callbackFn` + - : 配列内のそれぞれの値に対して実行するコールバック関数であり、 4 つの引数を取ります。 + - `accumulator` + - : コールバック関数の前回の呼び出しで返された値、もしくは、指定されていれば `initialValue` です。(下記参照) + - `currentValue` + - : 配列内で現在処理中の要素です。 + - `index`{{optional_inline}} + - : 配列内で現在処理中の要素の位置です。 + - `array`{{optional_inline}} + - : `reduceRight()` が呼び出された配列です。 -

畳み込みによって得られた 1 つの値です。

+- `initialValue` {{optional_inline}} + - : `callbackFn` の最初の呼び出しのときに、アキュームレーターとして使用する値です。初期値がが渡されなかった場合は、配列の最後の要素が適用され、その要素が飛ばされます。また、 reduce または reduceRight を空の配列に対して初期値なしで呼び出すと `TypeError` になります。 -

解説

+### 返値 -

reduceRight は、配列に存在する各要素に対して、callback 関数を一度だけ実行します。配列における穴は対象からはずされ、初期値(あるいは、直前の callback 呼び出し)、現在の要素の値、現在のインデックス、繰り返しが行われる配列の 4 つの引数を受け取ります。

+畳み込みによって得られた値です。 -

reduceRight の callback の呼び出しは、以下のように見えるでしょう。

+## 解説 -
array.reduceRight(function(accumulator, currentValue, index, array) {
+`reduceRight` は、配列内に存在するそれぞれの要素に対してコールバック関数を一度ずつ実行します。配列内の穴は対象外です。初期値 (あるいは直前のコールバックの呼び出し結果)、現在の要素の値、現在の位置、繰り返しが行われる配列の 4 つの引数を受け取ります。
+
+reduceRight の `callbackFn` の呼び出しは、以下のように見えるでしょう。
+
+```js
+arr.reduceRight(function(accumulator, currentValue, index, array) {
   // ...
 });
-
+``` -

関数が初めて呼び出されたとき、accumulatorcurrentValue は、2 つの値のいずれかになります。reduceRight の呼び出しで initialValue が指定された場合、accumulatorinitialValue と等しくなり、currentValue は配列の最後の値と等しくなります。initialValue が指定されなかった場合、accumulator は配列の最後の値に等しく、currentValue は最後から 2 番目の値に等しくなります。

+関数が初めて呼び出されたとき、`accumulator` と `currentValue` は、2 つの値のいずれかになります。 `initialValue` を指定して `reduceRight` を呼び出した場合、`accumulator` は `initialValue` と等しくなり、`currentValue` は配列の最後の値と等しくなります。`initialValue` が指定されなかった場合、`accumulator` は配列の最後の値に等しく、`currentValue` は最後から 2 番目の値に等しくなります。 -

配列が空で、initialValue が指定されていない場合、{{jsxref("TypeError")}} が投げられます。配列に要素が 1 つしかなく(位置に関係なく)、initialValue が指定されていない場合、または initialValue が指定されているが配列が空の場合、callback を呼び出さずに単独の値が返されます。

+配列が空で、`initialValue` が指定されなかった場合は、{{jsxref("TypeError")}} が発生します。配列に (位置に関わらず) 要素が 1 つしかなく、`initialValue` が指定されなかった場合、または `initialValue` が指定されたが配列が空だった場合は、`callbackFn` を呼び出されずに単独の値が返されます。 -

この関数を使用した場合について見てみましょう。

+この関数を使用した場合について見てみましょう。 -
[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) {
+```js
+[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) {
   return accumulator + currentValue;
 });
-
+``` -

コールバックは 4 回呼び出され、各コールの引数と戻り値は以下のようになります。

+コールバックは 4 回呼び出され、ぞれぞれの呼び出しの引数と返値は次のようになります。 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
callbackaccumulatorcurrentValueindexarrayreturn value
初回の呼出し433[0, 1, 2, 3, 4]7
2 回目の呼出し722[0, 1, 2, 3, 4]9
3 回目の呼出し911[0, 1, 2, 3, 4]10
4 回目の呼出し1000[0, 1, 2, 3, 4]10
+ callback + + accumulator + + currentValue + + index + + array + 返値
初回の呼び出し433[0, 1, 2, 3, 4]7
2 回目の呼び出し722[0, 1, 2, 3, 4]9
3 回目の呼び出し911[0, 1, 2, 3, 4]10
4 回目の呼び出し1000[0, 1, 2, 3, 4]10
-

reduceRight の返値は、コールバック呼び出しの最後の返値である (10) になります。

+`reduceRight` の返値は、コールバック呼び出しの最後の返値である (`10`) になります。 -

initialValue を与えた場合、その結果は以下のようになります。

+`initialValue` を渡した場合、結果は次のようになります。 -
[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) {
+```js
+[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) {
   return accumulator + currentValue;
 }, 10);
-
+``` - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
callbackaccumulatorcurrentValueindexarrayreturn value
初回の呼出し1044[0, 1, 2, 3, 4]14
2 回目の呼出し1433[0, 1, 2, 3, 4]17
3 回目の呼出し1722[0, 1, 2, 3, 4]19
4 回目の呼出し1911[0, 1, 2, 3, 4]20
5 回目の呼出し2000[0, 1, 2, 3, 4]20
+ callback + + accumulator + + currentValue + + index + + array + 返値
初回の呼び出し1044[0, 1, 2, 3, 4]14
2 回目の呼び出し1433[0, 1, 2, 3, 4]17
3 回目の呼び出し1722[0, 1, 2, 3, 4]19
4 回目の呼び出し1911[0, 1, 2, 3, 4]20
5 回目の呼び出し2000[0, 1, 2, 3, 4]20
-

この場合の reduceRight の返値は 20 になります。

+この場合の `reduceRight` の返値は `20` になります。 -

ポリフィル

+## ポリフィル -

reduceRight は ECMA-262 の第5版に追加されたもので、すべての実装には存在しない可能性があります。これを回避するには、スクリプトの最初に次のコードを挿入して、ネイティブにはサポートされていない実装でも reduceRight を使用できるようにします。

+`reduceRight` は ECMA-262 の第 5 版に追加されたもので、すべての実装には存在しない可能性があります。これを回避するには、スクリプトの最初に次のコードを挿入して、ネイティブには対応していない実装でも `reduceRight` を使用できるようにします。 -
// Production steps of ECMA-262, Edition 5, 15.4.4.22
-// Reference: http://es5.github.io/#x15.4.4.22
+```js
+// Production steps of ECMA-262, Edition 5, 15.4.4.22
+// Reference: https://es5.github.io/#x15.4.4.22
 if ('function' !== typeof Array.prototype.reduceRight) {
   Array.prototype.reduceRight = function(callback /*, initialValue*/) {
     'use strict';
@@ -200,19 +235,19 @@ if ('function' !== typeof Array.prototype.reduceRight) {
     if ('function' !== typeof callback) {
       throw new TypeError(callback + ' is not a function');
     }
-    var t = Object(this), len = t.length >>> 0, k = len - 1, value;
-    if (arguments.length >= 2) {
+    var t = Object(this), len = t.length >>> 0, k = len - 1, value;
+    if (arguments.length >= 2) {
       value = arguments[1];
     } else {
-      while (k >= 0 && !(k in t)) {
+      while (k >= 0 && !(k in t)) {
         k--;
       }
-      if (k < 0) {
+      if (k < 0) {
         throw new TypeError('Reduce of empty array with no initial value');
       }
       value = t[k--];
     }
-    for (; k >= 0; k--) {
+    for (; k >= 0; k--) {
       if (k in t) {
         value = callback(value, t[k], k, t);
       }
@@ -220,132 +255,115 @@ if ('function' !== typeof Array.prototype.reduceRight) {
     return value;
   };
 }
-
+``` -

+## 例 -

配列内のすべての値を合計する

+### 配列内のすべての値を合計する -
var sum = [0, 1, 2, 3].reduceRight(function(a, b) {
+```js
+var sum = [0, 1, 2, 3].reduceRight(function(a, b) {
   return a + b;
 });
 // sum is 6
-
+``` -

配列中の配列を平坦化する

+### 配列中の配列を平坦化する -
var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
+```js
+var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
     return a.concat(b);
 }, []);
 // flattened is [4, 5, 2, 3, 0, 1]
+```
 
-
+### 一連のコールバックを使用して非同期関数のリストを実行し、それぞれの結果を次のコールバックに渡す -

一連のコールバックを使用して非同期関数のリストを実行し、それぞれの結果を次のコールバックに渡す

- -
const waterfall = (...functions) => (callback, ...args) =>
+```js
+const waterfall = (...functions) => (callback, ...args) =>
   functions.reduceRight(
-    (composition, fn) => (...results) => fn(composition, ...results),
+    (composition, fn) => (...results) => fn(composition, ...results),
     callback
   )(...args);
 
-const randInt = max => Math.floor(Math.random() * max)
+const randInt = max => Math.floor(Math.random() * max)
 
-const add5 = (callback, x) => {
+const add5 = (callback, x) => {
   setTimeout(callback, randInt(1000), x + 5);
 };
-const mult3 = (callback, x) => {
+const mult3 = (callback, x) => {
   setTimeout(callback, randInt(1000), x * 3);
 };
-const sub2 = (callback, x) => {
+const sub2 = (callback, x) => {
   setTimeout(callback, randInt(1000), x - 2);
 };
-const split = (callback, x) => {
+const split = (callback, x) => {
   setTimeout(callback, randInt(1000), x, x);
 };
-const add = (callback, x, y) => {
+const add = (callback, x, y) => {
   setTimeout(callback, randInt(1000), x + y);
 };
-const div4 = (callback, x) => {
+const div4 = (callback, x) => {
   setTimeout(callback, randInt(1000), x / 4);
 };
 
 const computation = waterfall(add5, mult3, sub2, split, add, div4);
-computation(console.log, 5) // -> 14
+computation(console.log, 5) // -> 14
 
 // same as:
 
-const computation2 = (input, callback) => {
-  const f6 = x=> div4(callback, x);
-  const f5 = (x, y) => add(f6, x, y);
-  const f4 = x => split(f5, x);
-  const f3 = x => sub2(f4, x);
-  const f2 = x => mult3(f3, x);
+const computation2 = (input, callback) => {
+  const f6 = x=> div4(callback, x);
+  const f5 = (x, y) => add(f6, x, y);
+  const f4 = x => split(f5, x);
+  const f3 = x => sub2(f4, x);
+  const f2 = x => mult3(f3, x);
   add5(f2, input);
-}
+} +``` -

reducereduceRight の違い

+### `reduce` と `reduceRight` の違い -
var a = ['1', '2', '3', '4', '5'];
+```js
+var a = ['1', '2', '3', '4', '5'];
 var left  = a.reduce(function(prev, cur)      { return prev + cur; });
 var right = a.reduceRight(function(prev, cur) { return prev + cur; });
 
 console.log(left);  // "12345"
-console.log(right); // "54321"
+console.log(right); // "54321" +``` -

関数合計の定義

+### 合成可能な関数の定義 -

関数合成のコンセプトはシンプルで、n個の関数を組み合わせたものです。これは右から左へと流れ、最後の関数の出力を使用して各関数を呼び出します。

+関数合成とは、各関数の出力を次の関数に渡し、最後の関数の出力を最終的な結果とする、関数を組み合わせるための仕組みです。この例では `reduceRight()` を使って、関数合成を実現しています。 -
/**
- * Function Composition is way in which result of one function can
- * be passed to another and so on.
- *
- * h(x) = f(g(x))
- *
- * Function execution happens right to left
- *
- * https://en.wikipedia.org/wiki/Function_composition
- */
+Wikipedia の [Function composition]() も参照してください。
 
-const compose = (...args) => (value) => args.reduceRight((acc, fn) => fn(acc), value)
+```js
+const compose = (...args) => (value) => args.reduceRight((acc, fn) => fn(acc), value)
 
-// Increment passed number
-const inc = (n) => n + 1
+// 渡された数値をインクリメントする
+const inc = (n) => n + 1
 
-// Doubles the passed value
-const double = (n) => n * 2
+// 渡された数値を 2 倍にする
+const double = (n) => n * 2
 
-// using composition function
+// 合成関数を使用する
 console.log(compose(double, inc)(2)); // 6
 
-// using composition function
+// 合成関数を使用する
 console.log(compose(inc, double)(2)); // 5
-
- -

仕様

- - - - - - - - - - - - -
仕様書
{{SpecName('ESDraft', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}
+``` + +## 仕様書 + +{{Specifications}} -

ブラウザーの互換性

+## ブラウザーの互換性 -
-

{{Compat("javascript.builtins.Array.reduceRight")}}

-
+{{Compat}} -

関連情報

+## 関連情報 - +- `Array.prototype.reduceRight` のポリフィルが [`core-js`](https://github.com/zloirock/core-js#ecmascript-array) で利用できます +- {{jsxref("Array.prototype.reduce()")}} -- cgit v1.2.3-54-g00ecf