packages/core-api: added .with() as another way to construct ApiRegistries

This commit is contained in:
Patrik Oldsberg
2020-06-08 16:07:16 +02:00
parent 6567f241b5
commit f55959b680
2 changed files with 36 additions and 0 deletions
@@ -49,4 +49,20 @@ describe('ApiRegistry', () => {
expect(registry.get(x1Ref)).toBe(3);
expect(registry.get(x2Ref)).toBe('y');
});
it('should be created with API', () => {
const reg1 = ApiRegistry.with(x1Ref, 3);
const reg2 = reg1.with(x2Ref, 'y');
const reg3 = reg2.with(x2Ref, 'z');
const reg4 = reg3.with(x1Ref, 2);
expect(reg1.get(x1Ref)).toBe(3);
expect(reg1.get(x2Ref)).toBe(undefined);
expect(reg2.get(x1Ref)).toBe(3);
expect(reg2.get(x2Ref)).toBe('y');
expect(reg3.get(x1Ref)).toBe(3);
expect(reg3.get(x2Ref)).toBe('z');
expect(reg4.get(x1Ref)).toBe(2);
expect(reg4.get(x2Ref)).toBe('z');
});
});
+20
View File
@@ -42,8 +42,28 @@ export class ApiRegistry implements ApiHolder {
return new ApiRegistry(new Map(apis));
}
/**
* Creates a new ApiRegistry with a single API implementation.
*
* @param api ApiRef for the API to add
* @param impl Implementation of the API to add
*/
static with<T>(api: ApiRef<T>, impl: T): ApiRegistry {
return new ApiRegistry(new Map([[api, impl]]));
}
constructor(private readonly apis: Map<ApiRef<unknown>, unknown>) {}
/**
* Returns a new ApiRegistry with the provided API added to the existing ones.
*
* @param api ApiRef for the API to add
* @param impl Implementation of the API to add
*/
with<T>(api: ApiRef<T>, impl: T): ApiRegistry {
return new ApiRegistry(new Map([...this.apis, [api, impl]]));
}
get<T>(api: ApiRef<T>): T | undefined {
return this.apis.get(api) as T | undefined;
}