Skip to content

Commit

Permalink
Improve performance (#47)
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus authored Nov 25, 2020
1 parent b702cc1 commit 54c0ba8
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
17 changes: 9 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
'use strict';
const pTry = require('p-try');
const Queue = require('yocto-queue');

const pLimit = concurrency => {
if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) {
throw new TypeError('Expected `concurrency` to be a number from 1 and up');
}

const queue = [];
const queue = new Queue();
let activeCount = 0;

const next = () => {
activeCount--;

if (queue.length > 0) {
queue.shift()();
if (queue.size > 0) {
queue.dequeue()();
}
};

Expand All @@ -33,7 +34,7 @@ const pLimit = concurrency => {
};

const enqueue = (fn, resolve, ...args) => {
queue.push(run.bind(null, fn, resolve, ...args));
queue.enqueue(run.bind(null, fn, resolve, ...args));

(async () => {
// This function needs to wait until the next microtask before comparing
Expand All @@ -42,8 +43,8 @@ const pLimit = concurrency => {
// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
await Promise.resolve();

if (activeCount < concurrency && queue.length > 0) {
queue.shift()();
if (activeCount < concurrency && queue.size > 0) {
queue.dequeue()();
}
})();
};
Expand All @@ -54,11 +55,11 @@ const pLimit = concurrency => {
get: () => activeCount
},
pendingCount: {
get: () => queue.length
get: () => queue.size
},
clearQueue: {
value: () => {
queue.length = 0;
queue.clear();
}
}
});
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@
"bluebird"
],
"dependencies": {
"p-try": "^2.0.0"
"p-try": "^2.0.0",
"yocto-queue": "^0.1.0"
},
"devDependencies": {
"ava": "^2.4.0",
Expand Down

0 comments on commit 54c0ba8

Please sign in to comment.