Skip to content

Commit

Permalink
feat: allow add initial groups
Browse files Browse the repository at this point in the history
  • Loading branch information
barak007 committed Dec 4, 2023
1 parent 520c636 commit 9f2c2a7
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
8 changes: 5 additions & 3 deletions packages/patterns/src/disposables/create-disposables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,14 +70,16 @@ const withDefaults = (d?: DisposableOptions): Required<DisposableOptions> =>
* // 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}
Expand Down
21 changes: 20 additions & 1 deletion packages/patterns/src/test/disposables.unit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit 9f2c2a7

Please sign in to comment.