Skip to content

Commit

Permalink
Fix emitter.listenerCount() for symbol keys
Browse files Browse the repository at this point in the history
Fixes #113
  • Loading branch information
sindresorhus committed Jan 29, 2024
1 parent fc90205 commit fad52b9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
10 changes: 6 additions & 4 deletions index.js
Expand Up @@ -10,8 +10,10 @@ const listenerRemoved = Symbol('listenerRemoved');
let canEmitMetaEvents = false;
let isGlobalDebugEnabled = false;

const isEventKeyType = key => typeof key === 'string' || typeof key === 'symbol' || typeof key === 'number';

function assertEventName(eventName) {
if (typeof eventName !== 'string' && typeof eventName !== 'symbol' && typeof eventName !== 'number') {
if (!isEventKeyType(eventName)) {
throw new TypeError('`eventName` must be a string, symbol, or number');
}
}
Expand All @@ -32,7 +34,7 @@ function getListeners(instance, eventName) {
}

function getEventProducers(instance, eventName) {
const key = typeof eventName === 'string' || typeof eventName === 'symbol' || typeof eventName === 'number' ? eventName : anyProducer;
const key = isEventKeyType(eventName) ? eventName : anyProducer;
const producers = producersMap.get(instance);
if (!producers.has(key)) {
return;
Expand Down Expand Up @@ -432,7 +434,7 @@ export default class Emittery {
for (const eventName of eventNames) {
this.logIfDebugEnabled('clear', eventName, undefined);

if (typeof eventName === 'string' || typeof eventName === 'symbol' || typeof eventName === 'number') {
if (isEventKeyType(eventName)) {
const set = getListeners(this, eventName);
if (set) {
set.clear();
Expand Down Expand Up @@ -471,7 +473,7 @@ export default class Emittery {
let count = 0;

for (const eventName of eventNames) {
if (typeof eventName === 'string') {
if (isEventKeyType(eventName)) {
count += anyMap.get(this).size
+ (getListeners(this, eventName)?.size ?? 0)
+ (getEventProducers(this, eventName)?.size ?? 0)
Expand Down
12 changes: 12 additions & 0 deletions test/index.js
Expand Up @@ -1064,6 +1064,18 @@ test('listenerCount() - eventName must be undefined if not a string, symbol, or
}, {instanceOf: TypeError});
});

test('listenerCount() - symbol', t => {
const symbol = Symbol('🦄');
const emitter = new Emittery();
t.is(emitter.listenerCount(symbol), 0);
emitter.on(symbol, () => {});
emitter.on(symbol, () => {});
t.is(emitter.listenerCount(symbol), 2);
emitter.onAny(() => {});
emitter.onAny(() => {});
t.is(emitter.listenerCount(symbol), 4);
});

test('bindMethods()', t => {
const methodsToBind = ['on', 'off', 'emit', 'listenerCount'];

Expand Down

0 comments on commit fad52b9

Please sign in to comment.