/**
 * 遍历执行某个操作，达到指定数据长度时返回遍历结果
 *
 * @export
 * @param {*} arr 遍历对象
 * @param {*} limit 阈值，防止异步卡死
 * @param {*} iterator 迭代函数
 * @param {*} callback 回调函数
 * @return {*}
 */
export function eachLimit(arr, limit, iterator, callback) {
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  callback = callback || function () {};
  if (!arr.length || limit <= 0) {
    return callback(null, arr);
  }
  let completed = 0;
  let started = 0;
  let running = 0;
  (function replenish() {
    if (completed >= arr.length) {
      return callback(null, arr);
    }
    while (running < limit && started < arr.length) {
      started += 1;
      running += 1;
      // eslint-disable-next-line
      iterator(arr[started - 1], function (err) {
        if (err) {
          callback(err);
        } else {
          completed += 1;
          running -= 1;
          if (completed >= arr.length) {
            callback(null, arr);
          } else {
            replenish();
          }
        }
      });
    }
  })();
}