Skip to content

Commit

Permalink
fix-typing
Browse files Browse the repository at this point in the history
  • Loading branch information
uriva committed Jun 26, 2024
1 parent 862f547 commit 4e4e76d
Showing 1 changed file with 11 additions and 12 deletions.
23 changes: 11 additions & 12 deletions src/lock.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { AsyncFunction } from "./typing.ts";
import { sleep } from "./time.ts";
import { AsyncFunction } from "./typing.ts";

const withLock = <F extends AsyncFunction>(
lock: (...task: Parameters<F>) => void | Promise<void>,
Expand Down Expand Up @@ -86,7 +86,7 @@ export const rateLimit = <Function extends AsyncFunction>(
);
};

export const semaphore = (max: number) => {
const semaphore = (max: number) => {
let counter = 0;
const waiting: (() => void)[] = [];
const take = () => {
Expand Down Expand Up @@ -114,16 +114,15 @@ export const semaphore = (max: number) => {
};
};

export const throttle = <Function extends AsyncFunction>(max: number) => {
export const throttle = (max: number) => {
const { acquire, release } = semaphore(max);
return (f: Function) => {
return async (...args: Parameters<Function>) => {
await acquire();
try {
return await f(...args);
} finally {
release();
}
};
// @ts-expect-error too complex
return <F extends AsyncFunction>(f: F): F => async (...args) => {
await acquire();
try {
return await f(...args);
} finally {
release();
}
};
};

0 comments on commit 4e4e76d

Please sign in to comment.