JS Built-ins
DesignPatternsintermediate

Observer β€” Emit with no listeners

πŸ“– Usage Example
const emitter = createEmitter();
emitter.emit('test'); // no listeners β€” no error

Emitting with no listeners should be a no-op β€” not throw an error.

Observer Pattern β€” Safe Emit

The emit method should handle events that have no subscribers without throwing an error.

Challenge: Implement an EventEmitter that safely emits events even when no listeners are subscribed.

Example:

const emitter = new EventEmitter()
emitter.emit('nonexistent') // Should not throw
expect((() => { try { emitter.emit('test'); return true; } catch(e) { return false; } })()).toBe(true)
πŸ’‘ Hints (3)
  • β€’ Use nullish coalescing to default to empty array
  • β€’ forEach on empty array does nothing
  • β€’ No error handling needed if you use the nullish operator