1 | ;
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | /*-----------------------------------------------------------------------------
|
4 | | Copyright (c) 2014-2017, PhosphorJS Contributors
|
5 | |
|
6 | | Distributed under the terms of the BSD 3-Clause License.
|
7 | |
|
8 | | The full license is in the file LICENSE, distributed with this software.
|
9 | |----------------------------------------------------------------------------*/
|
10 | var iter_1 = require("./iter");
|
11 | function reduce(object, fn, initial) {
|
12 | // Setup the iterator and fetch the first value.
|
13 | var index = 0;
|
14 | var it = iter_1.iter(object);
|
15 | var first = it.next();
|
16 | // An empty iterator and no initial value is an error.
|
17 | if (first === undefined && initial === undefined) {
|
18 | throw new TypeError('Reduce of empty iterable with no initial value.');
|
19 | }
|
20 | // If the iterator is empty, return the initial value.
|
21 | if (first === undefined) {
|
22 | return initial;
|
23 | }
|
24 | // If the iterator has a single item and no initial value, the
|
25 | // reducer is not invoked and the first item is the return value.
|
26 | var second = it.next();
|
27 | if (second === undefined && initial === undefined) {
|
28 | return first;
|
29 | }
|
30 | // If iterator has a single item and an initial value is provided,
|
31 | // the reducer is invoked and that result is the return value.
|
32 | if (second === undefined) {
|
33 | return fn(initial, first, index++);
|
34 | }
|
35 | // Setup the initial accumlated value.
|
36 | var accumulator;
|
37 | if (initial === undefined) {
|
38 | accumulator = fn(first, second, index++);
|
39 | }
|
40 | else {
|
41 | accumulator = fn(fn(initial, first, index++), second, index++);
|
42 | }
|
43 | // Iterate the rest of the values, updating the accumulator.
|
44 | var next;
|
45 | while ((next = it.next()) !== undefined) {
|
46 | accumulator = fn(accumulator, next, index++);
|
47 | }
|
48 | // Return the final accumulated value.
|
49 | return accumulator;
|
50 | }
|
51 | exports.reduce = reduce;
|