From 3483a6c60e5cdb310cc202d03bd113886c0691a6 Mon Sep 17 00:00:00 2001 From: Michael Fabian 'Xaymar' Dirks Date: Sun, 19 Mar 2023 00:35:23 +0100 Subject: [PATCH] Add important comments to document functionality --- package.json | 2 +- source/ratelimiter.ts | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 9186f99..e66111d 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "A simple but effective way to rate limit Tasks in JavaScript.", "license": "GPLv3", "repository": "https://github.com/Xaymar/js-ratelimiter", - "version": "0.2.0", + "version": "0.2.1", "funding": { "type": "patreon", "url": "https://www.patreon.com/xaymar" diff --git a/source/ratelimiter.ts b/source/ratelimiter.ts index 1a10a00..8b7fca8 100644 --- a/source/ratelimiter.ts +++ b/source/ratelimiter.ts @@ -28,11 +28,18 @@ type RateLimiterAsyncExecutor = (...args: any[]) => Promise; type RateLimiterSyncExecutor = (...args: any[]) => any; type RateLimiterExecutor = RateLimiterSyncExecutor | RateLimiterAsyncExecutor; +/** A simple but effective way to rate limit Tasks. + * + */ export default class RateLimiter { private _maximum: number = 0; private _available: number = 0; 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) { if (!limit) { this._maximum = Math.ceil(Math.max(1, os.cpus().length / 3 * 2)); @@ -43,6 +50,12 @@ export default class RateLimiter { 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[]) { // Use async/await to find a free slot. while (this._available == 0) {