Sobes.tech
Middle+

Task: implement a class with subscribe, unsubscribe, and next methods (Observer pattern). All methods should be strictly typed in TypeScript. The subscribe method should return an unsubscribe function.

sobes.tech AI

Answer from AI

typescript class Observer<T> { private observers: Set<(data: T) => void> = new Set();

subscribe(fn: (data: T) => void): () => void { this.observers.add(fn); // Return unsubscribe function return () => this.unsubscribe(fn); }

unsubscribe(fn: (data: T) => void): void { this.observers.delete(fn); }

next(data: T): void { this.observers.forEach(fn => fn(data)); } }

// Example usage: const obs = new Observer<number>(); const unsubscribe = obs.subscribe(value => console.log('Received:', value)); obs.next(42); // Will output: Received: 42 unsubscribe(); obs.next(100); // Will not output anything

Task: implement a class with subscribe, unsubscribe… - sobes.tech