Sobes.tech
Middle+

Why did you choose an object for storing subscribers? How does unsubscription through filter work? What is the algorithm complexity of filter?

sobes.tech AI

Answer from AI

The object is chosen for storing subscribers because it provides quick access to subscribers by key (for example, ID or event name). This allows for efficient adding, removing, and searching for subscribers without having to traverse the entire list.

Unsubscribing via the filter method works as follows: you have an array of subscribers, and you create a new array that only includes those subscribers who are not equal to the one you want to unsubscribe from. This way, the subscriber is removed from the array.

Example:

let subscribers = [fn1, fn2, fn3];
// Unsubscribe fn2
subscribers = subscribers.filter(fn => fn !== fn2);

The complexity of the filter algorithm is O(n), where n is the number of elements in the array, since the method iterates over all elements, checking the condition.

Thus, unsubscribing via filter is a linear complexity operation, which may be inefficient with a large number of subscribers.

Why did you choose an object for storing subscribers… - sobes.tech