"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.delay = delay;
/**
* Creates a function that batches calls and delays execution.
* It ensures the 'targetFunction' is only called after a 'delayMs' wait period
* AND after the previous execution has finished.
*
* Batch and Delay, collects multiple requests into a single group
* and delays the execution of the target function.
*
* @param targetFunction the promise-returning function to delay,
*        targetFunction should take in a single array
* @param delayMs the number of milliseconds to delay
* @returns delayedFunc that takes an optional argument (array, single value, or nothing)
*/
function delay(targetFunction, delayMs) {
    let context;
    let itemsInQueue = [];
    let ongoingWorkPromise = Promise.resolve();
    let currentScheduledBatch = null;
    const sleep = (ms) => new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
    return function (newItem) {
        context = this;
        // Add new item to queue when called
        if (Array.isArray(newItem)) {
            itemsInQueue = itemsInQueue.concat(newItem);
        }
        else if (newItem) {
            itemsInQueue.push(newItem);
        }
        // Schedule a new batch if there is none scheduled
        if (currentScheduledBatch === null) {
            const batchPromise = Promise.all([sleep(delayMs), ongoingWorkPromise])
                .then(() => __awaiter(this, void 0, void 0, function* () {
                currentScheduledBatch = null;
                const itemsToProcess = [...itemsInQueue];
                itemsInQueue = [];
                return targetFunction.apply(context, [itemsToProcess]);
            }));
            currentScheduledBatch = batchPromise;
            ongoingWorkPromise = batchPromise.catch(() => { });
        }
        return currentScheduledBatch;
    };
}
//# sourceMappingURL=delay.js.map