aboutsummaryrefslogtreecommitdiff
path: root/files/uk/web/javascript/reference/global_objects/array/reduceright
diff options
context:
space:
mode:
authorPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
committerPeter Bengtsson <mail@peterbe.com>2020-12-08 14:43:23 -0500
commit218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (patch)
treea9ef8ac1e1b8fe4207b6d64d3841bfb8990b6fd0 /files/uk/web/javascript/reference/global_objects/array/reduceright
parent074785cea106179cb3305637055ab0a009ca74f2 (diff)
downloadtranslated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.gz
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.bz2
translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.zip
initial commit
Diffstat (limited to 'files/uk/web/javascript/reference/global_objects/array/reduceright')
-rw-r--r--files/uk/web/javascript/reference/global_objects/array/reduceright/index.html364
1 files changed, 364 insertions, 0 deletions
diff --git a/files/uk/web/javascript/reference/global_objects/array/reduceright/index.html b/files/uk/web/javascript/reference/global_objects/array/reduceright/index.html
new file mode 100644
index 0000000000..2471147574
--- /dev/null
+++ b/files/uk/web/javascript/reference/global_objects/array/reduceright/index.html
@@ -0,0 +1,364 @@
+---
+title: Array.prototype.reduceRight()
+slug: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight
+tags:
+ - Array
+ - ECMAScript5
+ - JavaScript
+ - Масив
+ - метод
+translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight
+---
+<div>{{JSRef}}</div>
+
+<p>Метод <code><strong>reduceRight()</strong></code> застосовує функцію до акумулятора та кожного елемента масиву (справа наліво), зменшуючи його до єдиного значення.</p>
+
+<div>{{EmbedInteractiveExample("pages/js/array-reduce-right.html")}}</div>
+
+
+
+<p>Дивіться також {{jsxref("Array.prototype.reduce()")}}, який виконується зліва направо.</p>
+
+<h2 id="Синтаксис">Синтаксис</h2>
+
+<pre class="syntaxbox"><var>arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])</var></pre>
+
+<h3 id="Параметри">Параметри</h3>
+
+<dl>
+ <dt><code>callback</code></dt>
+ <dd>Функція, яка виконується на кожному елементі масиву. Приймає чотири аргументи:
+ <dl>
+ <dt><code>accumulator</code></dt>
+ <dd>Значення, яке було повернене з попереднього виклику функції, або <code>initialValue</code>, якщо є. (Дивіться нижче.)</dd>
+ <dt><code>currentValue</code></dt>
+ <dd>Поточний елемент масиву, що опрацьовується.</dd>
+ <dt><code>index</code>{{optional_inline}}</dt>
+ <dd>Індекс поточного елемента масиву.</dd>
+ <dt><code>array</code>{{optional_inline}}</dt>
+ <dd>Масив, для якого було викликано <code>reduceRight()</code>.</dd>
+ </dl>
+ </dd>
+ <dt><code>initialValue</code>{{optional_inline}}</dt>
+ <dd>Значення, що використовується в якості акумулятора для першого виклику <code>callback</code>. Якщо початкового значення нема, то буде використаний та пропущений останній елемент масиву. Виклик <code>reduce</code> або <code>reduceRight</code> на порожньому масиві без початкового значення створить виняток <code>TypeError</code>.</dd>
+</dl>
+
+<h3 id="Значення_яке_повертається">Значення, яке повертається</h3>
+
+<p>Значення, що є результатом зменшення.</p>
+
+<h2 id="Опис">Опис</h2>
+
+<p>Метод <code>reduceRight</code> виконує функцію зворотного виклику один раз для кожного елемента у масиві, крім порожніх елементів, отримуючи чотири аргументи: початкове значення (або значення від попереднього виклику функції), значення поточного елемента, поточний індекс та масив, обхід якого виконується.</p>
+
+<p>Виклик функції <code>callback</code> у reduceRight виглядатиме десь так:</p>
+
+<pre class="brush: js">array.reduceRight(function(accumulator, currentValue, index, array) {
+ // ...
+});
+</pre>
+
+<p>Коли функція викликається вперше, <code>accumulator</code> та <code>currentValue</code> можуть мати одне з двох значень. Якщо значення <code>initialValue</code> було надане під час виклику <code>reduceRight</code>, тоді <code>accumulator</code> дорівнюватиме <code>initialValue</code>, а <code>currentValue</code> останньому елементу масиву. Якщо значення <code>initialValue</code> не визначено, тоді <code>accumulator</code> дорівнюватиме останньому елементу масиву, а <code>currentValue</code> передостанньому.</p>
+
+<p>Якщо масив порожній, а <code>initialValue</code> не надано, то буде викинуто виняток {{jsxref("TypeError")}}. Якщо масив має лише один елемент (незалежно від позиції), і немає значення <code>initialValue</code>, або якщо <code>initialValue</code> надано, але масив порожній, це єдине значення повернеться без виклику <code>callback</code>.</p>
+
+<p>Для прикладу, функція може виглядати так:</p>
+
+<pre class="brush: js">[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) {
+ return accumulator + currentValue;
+});
+</pre>
+
+<p>Функція зворотного виклику буде виконана чотири рази, аргументи та значення, які повертаються, наведені нижче:</p>
+
+<table>
+ <thead>
+ <tr>
+ <th scope="col"><code>callback</code></th>
+ <th scope="col"><code>accumulator</code></th>
+ <th scope="col"><code>currentValue</code></th>
+ <th scope="col"><code>index</code></th>
+ <th scope="col"><code>array</code></th>
+ <th scope="col">вертає</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <th scope="row">перший виклик</th>
+ <td><code>4</code></td>
+ <td><code>3</code></td>
+ <td><code>3</code></td>
+ <td><code>[0, 1, 2, 3, 4]</code></td>
+ <td><code>7</code></td>
+ </tr>
+ <tr>
+ <th scope="row">другий виклик</th>
+ <td><code>7</code></td>
+ <td><code>2</code></td>
+ <td><code>2</code></td>
+ <td><code>[0, 1, 2, 3, 4]</code></td>
+ <td><code>9</code></td>
+ </tr>
+ <tr>
+ <th scope="row">третій виклик</th>
+ <td><code>9</code></td>
+ <td><code>1</code></td>
+ <td><code>1</code></td>
+ <td><code>[0, 1, 2, 3, 4]</code></td>
+ <td><code>10</code></td>
+ </tr>
+ <tr>
+ <th scope="row">четвертий виклик</th>
+ <td><code>10</code></td>
+ <td><code>0</code></td>
+ <td><code>0</code></td>
+ <td><code>[0, 1, 2, 3, 4]</code></td>
+ <td><code>10</code></td>
+ </tr>
+ </tbody>
+</table>
+
+<p>Значення, яке повертає <code>reduceRight</code> буде тим, яке вертає останній виклик <code>callback</code> (<code>10</code>).</p>
+
+<p>А якби ви надали значення <code>initialValue</code>, результат виглядав би так:</p>
+
+<pre class="brush: js">[0, 1, 2, 3, 4].reduceRight(function(accumulator, currentValue, index, array) {
+ return accumulator + currentValue;
+}, 10);
+</pre>
+
+<table>
+ <thead>
+ <tr>
+ <th scope="col"><code>callback</code></th>
+ <th scope="col"><code>accumulator</code></th>
+ <th scope="col"><code>currentValue</code></th>
+ <th scope="col"><code>index</code></th>
+ <th scope="col"><code>array</code></th>
+ <th scope="col">вертає</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <th scope="row">перший виклик</th>
+ <td><code>10</code></td>
+ <td><code>4</code></td>
+ <td><code>4</code></td>
+ <td><code>[0, 1, 2, 3, 4]</code></td>
+ <td><code>14</code></td>
+ </tr>
+ <tr>
+ <th scope="row">другий виклик</th>
+ <td><code>14</code></td>
+ <td><code>3</code></td>
+ <td><code>3</code></td>
+ <td><code>[0, 1, 2, 3, 4]</code></td>
+ <td><code>17</code></td>
+ </tr>
+ <tr>
+ <th scope="row">третій виклик</th>
+ <td><code>17</code></td>
+ <td><code>2</code></td>
+ <td><code>2</code></td>
+ <td><code>[0, 1, 2, 3, 4]</code></td>
+ <td><code>19</code></td>
+ </tr>
+ <tr>
+ <th scope="row">четвертий виклик</th>
+ <td><code>19</code></td>
+ <td><code>1</code></td>
+ <td><code>1</code></td>
+ <td><code>[0, 1, 2, 3, 4]</code></td>
+ <td><code>20</code></td>
+ </tr>
+ <tr>
+ <th scope="row">п'ятий виклик</th>
+ <td><code>20</code></td>
+ <td><code>0</code></td>
+ <td><code>0</code></td>
+ <td><code>[0, 1, 2, 3, 4]</code></td>
+ <td><code>20</code></td>
+ </tr>
+ </tbody>
+</table>
+
+<p>Цього разу <code>reduceRight</code>, звісно, повернув би <code>20</code>.</p>
+
+<h2 id="Приклади">Приклади</h2>
+
+<h3 id="Знайти_суму_елементів_масиву">Знайти суму елементів масиву</h3>
+
+<pre class="brush: js">var sum = [0, 1, 2, 3].reduceRight(function(a, b) {
+ return a + b;
+});
+// сума дорівнює 6
+</pre>
+
+<h3 id="Вирівняти_масив_масивів">Вирівняти масив масивів</h3>
+
+<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
+ return a.concat(b);
+}, []);
+// Результат [4, 5, 2, 3, 0, 1]
+
+</pre>
+
+<h3 id="Виконати_послідовно_набір_асинхронних_функцій_з_функціями_зворотного_виклику_щоб_кожна_передавала_свій_результат_у_наступну">Виконати послідовно набір асинхронних функцій з функціями зворотного виклику, щоб кожна передавала свій результат у наступну</h3>
+
+<pre class="brush: js">const waterfall = (...functions) =&gt; (callback, ...args) =&gt;
+ functions.reduceRight(
+ (composition, fn) =&gt; (...results) =&gt; fn(composition, ...results),
+ callback
+ )(...args);
+
+const randInt = max =&gt; Math.floor(Math.random() * max)
+
+const add5 = (callback, x) =&gt; {
+ setTimeout(callback, randInt(1000), x + 5);
+};
+const mult3 = (callback, x) =&gt; {
+ setTimeout(callback, randInt(1000), x * 3);
+};
+const sub2 = (callback, x) =&gt; {
+ setTimeout(callback, randInt(1000), x - 2);
+};
+const split = (callback, x) =&gt; {
+ setTimeout(callback, randInt(1000), x, x);
+};
+const add = (callback, x, y) =&gt; {
+ setTimeout(callback, randInt(1000), x + y);
+};
+const div4 = (callback, x) =&gt; {
+ setTimeout(callback, randInt(1000), x / 4);
+};
+
+const computation = waterfall(add5, mult3, sub2, split, add, div4);
+computation(console.log, 5) // -&gt; 14
+
+// те саме, що й:
+
+const computation2 = (input, callback) =&gt; {
+ const f6 = x=&gt; div4(callback, x);
+ const f5 = (x, y) =&gt; add(f6, x, y);
+ const f4 = x =&gt; split(f5, x);
+ const f3 = x =&gt; sub2(f4, x);
+ const f2 = x =&gt; mult3(f3, x);
+ add5(f2, input);
+}</pre>
+
+<h3 id="Різниця_між_reduce_та_reduceRight">Різниця між <code>reduce</code> та <code>reduceRight</code></h3>
+
+<pre class="brush: 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"</pre>
+
+<h3 id="Визначення_композиції_функцій">Визначення композиції функцій</h3>
+
+<p>Концепція композиції функцій проста - вона об'єднує функції. Це послідовний, справа наліво, виклик кожної функції з результатом попередньої.</p>
+
+<pre class="brush: js">/**
+ * Композиція функцій - це підхід, в якому результат однієї функції
+ * передається у іншу і т.д.
+ *
+ * h(x) = f(g(x))
+ *
+ * Виконання функцій відбувається справа наліво
+ *
+ * <a href="https://uk.wikipedia.org/wiki/Композиція_функцій">https://uk.wikipedia.org/wiki/Композиція_функцій</a>
+ */
+
+const compose = (...args) =&gt; (value) =&gt; args.reduceRight((acc, fn) =&gt; fn(acc), value)
+
+// Збільшує передане число на 1
+const inc = (n) =&gt; n + 1
+
+// Подвоює передане значення
+const double = (n) =&gt; n * 2
+
+// використання композиції функцій
+console.log(compose(double, inc)(2)); // 6
+
+// використання композиції функцій
+console.log(compose(inc, double)(2)); // 5
+</pre>
+
+<h2 id="Поліфіл">Поліфіл</h2>
+
+<p>Метод <code>reduceRight</code> був доданий до стандарту ECMA-262 у 5-й версії; таким чином, він може не бути присутній у всіх реалізаціях стандарту. Ви можете обійти цю проблему, вставивши наступний код на початку ваших скриптів, це дозволить використовувати метод <code>reduceRight</code> у версіях, які не підтримують його початково.</p>
+
+<pre class="brush: js">// Функціональні кроки ECMA-262, версія 5, 15.4.4.22
+// Довідка: http://es5.github.io/#x15.4.4.22
+if ('function' !== typeof Array.prototype.reduceRight) {
+ Array.prototype.reduceRight = function(callback /*, initialValue*/) {
+ 'use strict';
+ if (null === this || 'undefined' === typeof this) {
+ throw new TypeError('Array.prototype.reduce called on null or undefined');
+ }
+ if ('function' !== typeof callback) {
+ throw new TypeError(callback + ' is not a function');
+ }
+ var t = Object(this), len = t.length &gt;&gt;&gt; 0, k = len - 1, value;
+ if (arguments.length &gt;= 2) {
+ value = arguments[1];
+ } else {
+ while (k &gt;= 0 &amp;&amp; !(k in t)) {
+ k--;
+ }
+ if (k &lt; 0) {
+ throw new TypeError('Reduce of empty array with no initial value');
+ }
+ value = t[k--];
+ }
+ for (; k &gt;= 0; k--) {
+ if (k in t) {
+ value = callback(value, t[k], k, t);
+ }
+ }
+ return value;
+ };
+}
+</pre>
+
+<h2 id="Специфікації">Специфікації</h2>
+
+<table class="standard-table">
+ <tbody>
+ <tr>
+ <th scope="col">Специфікація</th>
+ <th scope="col">Статус</th>
+ <th scope="col">Коментар</th>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES5.1', '#sec-15.4.4.22', 'Array.prototype.reduceRight')}}</td>
+ <td>{{Spec2('ES5.1')}}</td>
+ <td>Початкове визначення. Реалізоване у JavaScript 1.8.</td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ES6', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}</td>
+ <td>{{Spec2('ES6')}}</td>
+ <td></td>
+ </tr>
+ <tr>
+ <td>{{SpecName('ESDraft', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}</td>
+ <td>{{Spec2('ESDraft')}}</td>
+ <td></td>
+ </tr>
+ </tbody>
+</table>
+
+<h2 id="Сумісність_з_веб-переглядачами">Сумісність з веб-переглядачами</h2>
+
+<div>
+
+
+<p>{{Compat("javascript.builtins.Array.reduceRight")}}</p>
+</div>
+
+<h2 id="Див._також">Див. також</h2>
+
+<ul>
+ <li>{{jsxref("Array.prototype.reduce()")}}</li>
+</ul>