From 9f2c2a7ce1df9e5084cf8e980b3953eefc98955a Mon Sep 17 00:00:00 2001 From: Barak Date: Mon, 4 Dec 2023 12:04:10 +0200 Subject: [PATCH] feat: allow add initial groups --- .../src/disposables/create-disposables.ts | 8 ++++--- .../patterns/src/test/disposables.unit.ts | 21 ++++++++++++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/packages/patterns/src/disposables/create-disposables.ts b/packages/patterns/src/disposables/create-disposables.ts index 83fd48a5..65bdcc01 100644 --- a/packages/patterns/src/disposables/create-disposables.ts +++ b/packages/patterns/src/disposables/create-disposables.ts @@ -70,14 +70,16 @@ const withDefaults = (d?: DisposableOptions): Required => * // last * ``` */ -export function createDisposables() { - return new Disposables(); +export function createDisposables(initialGroups: string[] = []) { + return new Disposables(initialGroups); } export class Disposables { private readonly groups: DisposalGroup[] = [createGroup(DEFAULT_GROUP)]; private readonly constrains: GroupConstraints[] = []; - + constructor(initialGroups: string[] = []) { + this.groups.push(...initialGroups.map(createGroup)); + } /** * register a new constrained disposal group * @param constraints - constraints for the group must contain {before: groupName} or {after: groupName} diff --git a/packages/patterns/src/test/disposables.unit.ts b/packages/patterns/src/test/disposables.unit.ts index d3c8b066..a930e51a 100644 --- a/packages/patterns/src/test/disposables.unit.ts +++ b/packages/patterns/src/test/disposables.unit.ts @@ -40,7 +40,26 @@ describe('disposables', () => { await expect(disposables.dispose()).to.eventually.be.rejectedWith('Disposal timed out: "slow"'); }); }); - + describe('initial disposal group', () => { + it('disposes in insertion order', async () => { + const disposed: number[] = []; + const disposables = createDisposables(['A', 'B']); + disposables.add(() => disposed.push(2), 'B'); + disposables.add(() => disposed.push(1), 'A'); + await disposables.dispose(); + expect(disposed).to.deep.equal([1, 2]); + }); + it('allow adding additional groups', async () => { + const disposed: number[] = []; + const disposables = createDisposables(['A', 'C']); + disposables.registerGroup('B', { before: 'C' }); + disposables.add(() => disposed.push(1), 'A'); + disposables.add(() => disposed.push(2), 'B'); + disposables.add(() => disposed.push(3), 'C'); + await disposables.dispose(); + expect(disposed).to.deep.equal([1, 2, 3]); + }); + }); describe('disposal groups', () => { describe('constraints validation', () => { it('throws for missing groups', () => {