"use strict";
/*!
  Copyright 2018 Ron Buckton (rbuckton@chronicles.org)

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
 */
/** @module "iterable-query/fn" */
Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = require("tslib");
var internal_1 = require("../internal");
var toArrayAsync_1 = require("./toArrayAsync");
var common_1 = require("./common");
function reduceRightAsync(source, accumulator, seed, resultSelector) {
    if (resultSelector === void 0) { resultSelector = common_1.identity; }
    return reduceRightAsyncCore(source, accumulator, seed, arguments.length > 2, resultSelector);
}
exports.reduceRightAsync = reduceRightAsync;
function reduceRightAsyncCore(source, accumulator, current, hasCurrent, resultSelector) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var sourceArray, count, offset, value;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    internal_1.assert.mustBeAsyncQueryable(source, "source");
                    internal_1.assert.mustBeFunction(accumulator, "accumulator");
                    internal_1.assert.mustBeFunction(resultSelector, "resultSelector");
                    return [4 /*yield*/, toArrayAsync_1.toArrayAsync(source)];
                case 1:
                    sourceArray = _a.sent();
                    count = 0;
                    offset = sourceArray.length - 1;
                    _a.label = 2;
                case 2:
                    if (!(offset >= 0)) return [3 /*break*/, 7];
                    value = sourceArray[offset];
                    if (!!hasCurrent) return [3 /*break*/, 3];
                    current = value;
                    hasCurrent = true;
                    return [3 /*break*/, 5];
                case 3: return [4 /*yield*/, accumulator(current, value, offset)];
                case 4:
                    current = _a.sent();
                    _a.label = 5;
                case 5:
                    count++;
                    _a.label = 6;
                case 6:
                    offset--;
                    return [3 /*break*/, 2];
                case 7: return [2 /*return*/, resultSelector(current, count)];
            }
        });
    });
}
//# sourceMappingURL=reduceRightAsync.js.map