Add important comments to document functionality
This commit is contained in:
+1
-1
@@ -4,7 +4,7 @@
|
|||||||
"description": "A simple but effective way to rate limit Tasks in JavaScript.",
|
"description": "A simple but effective way to rate limit Tasks in JavaScript.",
|
||||||
"license": "GPLv3",
|
"license": "GPLv3",
|
||||||
"repository": "https://github.com/Xaymar/js-ratelimiter",
|
"repository": "https://github.com/Xaymar/js-ratelimiter",
|
||||||
"version": "0.2.0",
|
"version": "0.2.1",
|
||||||
"funding": {
|
"funding": {
|
||||||
"type": "patreon",
|
"type": "patreon",
|
||||||
"url": "https://www.patreon.com/xaymar"
|
"url": "https://www.patreon.com/xaymar"
|
||||||
|
|||||||
@@ -28,11 +28,18 @@ type RateLimiterAsyncExecutor = (...args: any[]) => Promise<any>;
|
|||||||
type RateLimiterSyncExecutor = (...args: any[]) => any;
|
type RateLimiterSyncExecutor = (...args: any[]) => any;
|
||||||
type RateLimiterExecutor = RateLimiterSyncExecutor | RateLimiterAsyncExecutor;
|
type RateLimiterExecutor = RateLimiterSyncExecutor | RateLimiterAsyncExecutor;
|
||||||
|
|
||||||
|
/** A simple but effective way to rate limit Tasks.
|
||||||
|
*
|
||||||
|
*/
|
||||||
export default class RateLimiter {
|
export default class RateLimiter {
|
||||||
private _maximum: number = 0;
|
private _maximum: number = 0;
|
||||||
private _available: number = 0;
|
private _available: number = 0;
|
||||||
private _instances: any[];
|
private _instances: any[];
|
||||||
|
|
||||||
|
/** Create a new instance of a RateLimiter.
|
||||||
|
*
|
||||||
|
* @param limit The maximum number of tasks that should run in parallel. The Default is 2/3rds of the available CPU threads.
|
||||||
|
*/
|
||||||
constructor(limit?: number) {
|
constructor(limit?: number) {
|
||||||
if (!limit) {
|
if (!limit) {
|
||||||
this._maximum = Math.ceil(Math.max(1, os.cpus().length / 3 * 2));
|
this._maximum = Math.ceil(Math.max(1, os.cpus().length / 3 * 2));
|
||||||
@@ -43,6 +50,12 @@ export default class RateLimiter {
|
|||||||
this._instances = [];
|
this._instances = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Queue up a new task.
|
||||||
|
*
|
||||||
|
* @param executor The function that should be run eventually.
|
||||||
|
* @param args Optional arguments to pass to the function.
|
||||||
|
* @returns A Promise that resolves with the result of the function.
|
||||||
|
*/
|
||||||
async queue(executor: RateLimiterExecutor, ...args: any[]) {
|
async queue(executor: RateLimiterExecutor, ...args: any[]) {
|
||||||
// Use async/await to find a free slot.
|
// Use async/await to find a free slot.
|
||||||
while (this._available == 0) {
|
while (this._available == 0) {
|
||||||
|
|||||||
Reference in New Issue
Block a user