Mark As Completed Discussion

The Brute-Force Approach: The First Draft

The First Draft

Data Structure Choices

Our first instinct for the brute-force approach is to use a simple JavaScript object to keep track of event subscriptions. Each key in the object would correspond to an eventName, and the value would be an array of callback functions.

Functionality

The subscribe method would push the callback function into the array associated with the eventName. The emit method would then loop through this array and execute all the callbacks.

Issues

However, this approach has its limitations:

  • It does not account for duplicate callbacks.
  • Removing a specific callback (unsubscribing) would be inefficient because we'd have to find it in the array and remove it.

Optimizing: Refining the Solution

Given the issues with the brute-force approach, let's look for ways to optimize.

The First Draft

Using a Map

We can use a Map data structure for the subscriptions property to take advantage of its quick lookup and insertion capabilities. Maps also maintain the insertion order, which could be beneficial if the order of events mattered.

Using a Set for Callbacks

Instead of using an array for callbacks, we can use a Set. This would automatically take care of duplicate callbacks, as Sets only store unique values.

Efficient Unsubscription

We also need an efficient way to unsubscribe from events. For this, we can return a release function from the subscribe method. This function would remove the subscriber's callback from the Set, making unsubscription as simple as calling a function.