"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.waitFor = void 0;

/**
 * @param {any} store
 * @param {string} selectorName
 * @param {{ timeout: number }} [opts]
 * @returns {Promise<void>}
 */
const waitFor = (store, selectorName, {
  timeout
} = {}) => new Promise((resolve, reject) => {
  const conditionMatched = () => store[selectorName]();

  if (conditionMatched()) {
    return resolve();
  }

  let timerId;
  const unsubscribe = store.subscribeToSelectors([selectorName], () => {
    if (conditionMatched()) {
      clearTimeout(timerId);
      unsubscribe();
      return resolve();
    }
  });

  if (timeout) {
    timerId = setTimeout(() => {
      // cleanup
      unsubscribe();
      reject(Error('TIMED_OUT'));
    }, timeout);
  }
});

exports.waitFor = waitFor;