Fix the replay of a chat screen's sockets
Your task
Your React Native chat screen shows each message two, three, four times as users navigate in and out, and memory keeps climbing. Its hook opened a socket in an effect but returned no cleanup, so old listeners stayed alive. A cleanup is the function an effect returns, which React runs before the effect runs again and on unmount. To check the fix, the team wants a replay of the screen with the cleanup in place.
An assistant wrote replay_chat_messages(events). It is in the editor. It has a bug. Find it and fix it.
Input and output:
events: the event log, as strings, in order. It can be empty.- Return the messages the screen holds after the last event, in the order they arrived.
Rules the tests check:
- Events and room names are case sensitive. At most one socket is open at any time.
"mount:<room>": the screen mounts. Any open socket closes first. The message list becomes empty, and the screen listens to<room>. An empty room name means ignore the event."room:<room>": the room changes while the screen is mounted. The old socket closes and a socket for<room>opens. The message list is kept. Ignore the event when the screen is not mounted or the room name is empty."unmount": the socket closes, the screen is no longer mounted, and the message list becomes empty."emit:<room>|<text>": the server sends<text>to<room>. The room is everything before the first"|"and the text is everything after it, so the text can be empty or contain"|". With no"|", ignore the event.- An emit adds its text to the list exactly once when the screen is mounted and listening to that room. Otherwise it adds nothing.
- Ignore any other event.
Examples
replay_chat_messages(events: list[str]) -> list[str]Example 1
Input
replay_chat_messages(["mount:general", "emit:general|hello", "emit:general|world"])Output
["hello", "world"]Example 2
Input
replay_chat_messages(["mount:general", "room:random", "emit:general|stale", "emit:random|fresh"])Output
["fresh"]Example 3
Input
replay_chat_messages(["mount:general", "emit:general|hi", "unmount", "emit:general|hi"])Output
[]