"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createDebounceManager = void 0;
function _toConsumableArray(r) { return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _iterableToArray(r) { if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r); }
function _arrayWithoutHoles(r) { if (Array.isArray(r)) return _arrayLikeToArray(r); }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
/**
 * Creates a debounce manager for the given function
 * Use case: a debounced function (eg. change handler) has to be synchronized in order to work with the most recent data
 * Note: invokeSync and sync can work with async/await (result forwarding)
 * @author boda@redhotmagma.de
 * @param {function} callbackFn
 * @param {number} delay The delay in ms
 */
var createDebounceManager = exports.createDebounceManager = function createDebounceManager(callbackFn) {
  var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 200;
  var lastChangeTimeout;
  var needsInvocation = false;
  var storedArgs = [];
  var invokeStored = function invokeStored() {
    if (needsInvocation) {
      needsInvocation = false;
      return callbackFn.apply(void 0, _toConsumableArray(storedArgs));
    }
  };
  return {
    /**
     * @param args
     * @return {*}
     */
    invokeSync: function invokeSync() {
      window.clearTimeout(lastChangeTimeout);
      needsInvocation = false;
      return callbackFn.apply(void 0, arguments);
    },
    /**
     * @param args
     */
    invokeDebounced: function invokeDebounced() {
      window.clearTimeout(lastChangeTimeout);
      needsInvocation = true;
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      storedArgs = args;
      lastChangeTimeout = window.setTimeout(invokeStored, delay);
    },
    /**
     * @return {*}
     */
    sync: function sync() {
      window.clearTimeout(lastChangeTimeout);
      return invokeStored();
    }
  };
};