diff --git a/packages/core-api/src/apis/ApiRegistry.test.ts b/packages/core-api/src/apis/ApiRegistry.test.ts index 2971397e7a..a859d51004 100644 --- a/packages/core-api/src/apis/ApiRegistry.test.ts +++ b/packages/core-api/src/apis/ApiRegistry.test.ts @@ -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'); + }); }); diff --git a/packages/core-api/src/apis/ApiRegistry.ts b/packages/core-api/src/apis/ApiRegistry.ts index 0a9d14a4e7..64d97ba234 100644 --- a/packages/core-api/src/apis/ApiRegistry.ts +++ b/packages/core-api/src/apis/ApiRegistry.ts @@ -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(api: ApiRef, impl: T): ApiRegistry { + return new ApiRegistry(new Map([[api, impl]])); + } + constructor(private readonly apis: Map, 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(api: ApiRef, impl: T): ApiRegistry { + return new ApiRegistry(new Map([...this.apis, [api, impl]])); + } + get(api: ApiRef): T | undefined { return this.apis.get(api) as T | undefined; }