Skip to content

Commit

Permalink
feat: 🎸 add support for arguments in mutex decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Mar 9, 2024
1 parent d650797 commit 7095e93
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
14 changes: 14 additions & 0 deletions src/__tests__/mutex.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,17 @@ test('works as a class method decorator', async () => {
const res4 = await test.code();
expect(res4).toStrictEqual(3);
});

test('passes through arguments in the decorated method', async () => {
let cnt = 0;
class Test {
@mutex async code(divisor: number) {
return cnt++ / divisor;
}
}
const test = new Test();
const res = await Promise.all([test.code(10), test.code(10), test.code(10)]);
expect(res).toStrictEqual([0, 0, 0]);
const res2 = await Promise.all([test.code(10), test.code(10), test.code(10), test.code(10)]);
expect(res2).toStrictEqual([0.1, 0.1, 0.1, 0.1]);
});
10 changes: 5 additions & 5 deletions src/mutex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import {codeMutex} from './codeMutex';
* {@link mutex} can be used as a class method decorator or a higher order
* function.
*/
export function mutex<This, Return>(
target: (this: This) => Promise<Return>,
context?: ClassMethodDecoratorContext<This, (this: This) => Promise<Return>>,
export function mutex<This, Args extends any[], Return>(
target: (this: This, ...args: Args) => Promise<Return>,
context?: ClassMethodDecoratorContext<This, (this: This, ...args: Args) => Promise<Return>>,
) {
const mut = codeMutex<Return>();
return async function (this: This): Promise<Return> {
return await mut(async () => await target.call(this));
return async function (this: This, ...args: Args): Promise<Return> {
return await mut(async () => await target.call(this, ...args));
};
}

0 comments on commit 7095e93

Please sign in to comment.