Skip to content

Commit

Permalink
Parameterising resource acquisitions
Browse files Browse the repository at this point in the history
  • Loading branch information
CMCDragonkai committed Apr 22, 2022
1 parent 318a517 commit 823f527
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 7 deletions.
8 changes: 4 additions & 4 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
type ResourceAcquire<Resource = void> = () => Promise<
readonly [ResourceRelease, Resource?]
>;
type ResourceAcquire<Resource> = (
resources: readonly any[],
) => Promise<readonly [ResourceRelease, Resource?]>;

type ResourceRelease = (e?: Error) => Promise<void>;

type Resources<T extends readonly ResourceAcquire<any>[]> = {
type Resources<T extends readonly ResourceAcquire<unknown>[]> = {
[K in keyof T]: T[K] extends ResourceAcquire<infer R> ? R : never;
};

Expand Down
4 changes: 2 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ async function withF<
let e_: Error | undefined;
try {
for (const acquire of acquires) {
const [release, resource] = await acquire();
const [release, resource] = await acquire(resources);
releases.push(release);
resources.push(resource);
}
Expand Down Expand Up @@ -54,7 +54,7 @@ async function* withG<
let e_: Error | undefined;
try {
for (const acquire of acquires) {
const [release, resource] = await acquire();
const [release, resource] = await acquire(resources);
releases.push(release);
resources.push(resource);
}
Expand Down
35 changes: 34 additions & 1 deletion tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ describe('index', () => {
// Multiple resources outside requires type declaration
const resourceAcquires6: [
ResourceAcquire<number>,
ResourceAcquire,
ResourceAcquire<void>,
ResourceAcquire<string>,
] = [
async () => {
Expand Down Expand Up @@ -246,4 +246,37 @@ describe('index', () => {
expect(acquireOrder).toStrictEqual([lock1, lock2]);
expect(releaseOrder).toStrictEqual([lock2, lock1]);
});
test('withF parameterised resources', async () => {
await withF(
[
async () => [async () => {}, 1],
async ([a]) => [async () => {}, a + 1],
async ([, b]) => [async () => {}, b + 1],
],
async ([a, b, c]) => {
expect(a).toBe(1);
expect(b).toBe(2);
expect(c).toBe(3);
},
);
});
test('withG parameterised resources', async () => {
const g = withG(
[
async () => [async () => {}, 1],
async ([a]) => [async () => {}, a + 1],
async ([, b]) => [async () => {}, b + 1],
],
async function* ([a, b, c]): AsyncGenerator<number> {
yield a;
yield b;
yield c;
},
);
let counter = 1;
for await (const r of g) {
expect(r).toBe(counter);
counter++;
}
});
});

0 comments on commit 823f527

Please sign in to comment.