Fix the replay that counts leaked resize listeners
Your task
A responsive layout hook adds a resize listener in an effect with an empty dependency list, and returns no cleanup. After a few page changes the app slows down, and the team wants a replay that counts the listeners still registered.
An assistant wrote active_listener_count(lifecycle_events, has_cleanup). It is in the editor. It has a bug. Find it and fix it.
Input and output:
lifecycle_events: the component's lifecycle events, in order, such as"mount","unmount"and"rerender". A recording can start after the component mounted.has_cleanup: true when the effect returns a teardown function that removes the listener, false when it returns nothing.- Return the number of listeners still registered at the end, as an integer.
Rules the tests check:
- Start with 0 listeners.
"mount": the effect runs and adds 1 listener."unmount": whenhas_cleanupis true, the teardown removes 1 listener. When it is false, nothing is removed.- An
"unmount"when no listener is registered removes nothing. The count never goes below 0. - Any other event, such as
"rerender", changes nothing. An effect with an empty dependency list runs once per mount, not once per render. - Event names are case sensitive, so
"MOUNT"changes nothing. - No events returns 0.
Examples
active_listener_count(lifecycle_events: list[str], has_cleanup: bool) -> intExample 1
Input
active_listener_count(["mount", "unmount", "mount", "unmount"], True)Output
0Example 2
Input
active_listener_count(["mount", "unmount", "mount", "unmount"], False)Output
2Example 3
Input
active_listener_count(["mount"], True)Output
1