Skip to content

Commit

Permalink
exposing maxSubs as read-only property
Browse files Browse the repository at this point in the history
  • Loading branch information
vitaly-t committed Aug 5, 2019
1 parent 7ba619c commit 01b18f9
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "sub-events",
"version": "0.5.5",
"version": "0.6.0",
"description": "Strongly-typed events in TypeScript, with monitored subscriptions.",
"main": "dist/src/index.js",
"types": "dist/src/index.d.ts",
Expand Down
14 changes: 12 additions & 2 deletions src/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,17 @@ export class SubEvent<T = unknown> {
return this._subs.length;
}

/**
* Maximum number of subscribers that can receive events.
* Default is 0, meaning `no limit applies`.
*
* As the older subscriptions get cancelled, the newer ones
* outside of the maximum quota will start receiving events.
*/
public get maxSubs(): number {
return this.options.maxSubs || 0;
}

/**
* Cancels all subscriptions.
*
Expand Down Expand Up @@ -303,8 +314,7 @@ export class SubEvent<T = unknown> {
* @hidden
*/
protected _getRecipients(): ISubscriber<T>[] {
const max = this.options.maxSubs || 0;
const end = max > 0 ? max : this._subs.length;
const end = this.maxSubs > 0 ? this.maxSubs : this._subs.length;
return this._subs.slice(0, end);
}

Expand Down
6 changes: 6 additions & 0 deletions test/event.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ const dummy = () => {
};

describe('SubEvent', () => {
it('must initialize correctly', () => {
const a = new SubEvent();
expect(a.count).to.eq(0);
expect(a.maxSubs).to.eq(0);
});
it('must invoke subscription functions', () => {
const a = new SubEvent<number>();
const cb = () => 1;
Expand Down Expand Up @@ -70,6 +75,7 @@ describe('SubEvent', () => {
const s2 = chai.spy(cb2);
a.subscribe(s1);
a.subscribe(s2);
expect(a.maxSubs).to.eq(1);
expect(a.count).to.eq(2);
a.emit(123, (count: number) => {
expect(count).to.be.eq(1);
Expand Down

0 comments on commit 01b18f9

Please sign in to comment.