"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:true});exports.default=void 0;var _slicedToArray2=_interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));var _isPositiveInteger=_interopRequireDefault(require("./isPositiveInteger"));
var _lockAsync=_interopRequireDefault(require("./lockAsync"));var _default=





(func,numConcurrent=Infinity)=>{
if(numConcurrent===Infinity){
return func;
}

if(!(0,_isPositiveInteger.default)(numConcurrent)){
const msg="numConcurrent should be a positive integer or Infinity";
throw new Error(`${msg}. Instead got: ${numConcurrent}`);
}

if(numConcurrent===1){

return(0,_lockAsync.default)(func);
}

const pool=new Set;
const queue=[];

function attach(p){
p.then(()=>{
pool.delete(p);
const o=queue.shift();
if(!o){
return;
}const _o=(0,_slicedToArray2.default)(

o,2),args=_o[0],resolve=_o[1];
const newP=func(...args).then(resolve);
attach(newP);
pool.add(newP);
});
}


return(...args)=>{
if(pool.size<numConcurrent){
const p=func(...args);
attach(p);
pool.add(p);
return p;
}

return new Promise(resolve=>{
queue.push([args,resolve]);
});
};
};exports.default=_default;