Skip to content

aviyadeveloper/event-bus-challenge

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

EventBus

TypeScript implementation of an event bus with priority-based listener execution.

Installation

npm install

Commands

npm test              # Run tests
npm run dev:match     # Run soccer match example
npm run dev:download  # Run download queue example
npm run build         # Build project

EventBus Usage

import { EventBus } from "./EventBus";
import { Event, EventPriority } from "./types";

type UserEvent = Event<"user:login", { userId: string }>;

const eventBus = new EventBus();

eventBus.on<UserEvent>("user:login", (event) => {
  console.log(`User ${event.data.userId} logged in`);
});

eventBus.post<UserEvent>({
  type: "user:login",
  timestamp: Date.now(),
  data: { userId: "123" },
});

DownloadQueue Usage

import { EventBus } from "./EventBus";
import { DownloadQueue } from "./DownloadQueue";

const eventBus = new EventBus();

// Sync mode: downloads sequentially, events fire in order
const syncQueue = new DownloadQueue(eventBus, { mode: "sync" });
await syncQueue.download(["url1", "url2", "url3"]);

// Async mode: downloads concurrently, events fire as ready
const asyncQueue = new DownloadQueue(eventBus, { mode: "async" });
await asyncQueue.download(["url1", "url2", "url3"]);

Run demo: npm run dev:download

API

on(eventType, listener, options?) - Register a listener
off(eventType, listener) - Unregister a listener
post(event) - Post an event to listeners
clear(eventType?) - Remove listeners
listenerCount(eventType) - Get listener count
eventTypes() - Get registered event types

Priority

Listeners execute in priority order (highest first):

eventBus.on("event", listener1, { priority: EventPriority.HIGH });
eventBus.on("event", listener2, { priority: EventPriority.NORMAL });

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published