Generate and Delete a Message in the Chat List

Introduction

So far, we've implemented the class to handle our chat list and a few utility functions. We'll write a script in later lessons to either randomly generate a new message from a user or randomly delete a message from a user. Now, we are going to implement the three functions mentioned below:

  1. A function to handle the scenario when a new message is generated.

  2. A function to handle the scenario when a message is deleted.

  3. A function to update the chat list when either of the above two operations occurs.

Implement the scenario for a new message

When a new message is generated, there can be two scenarios:

  1. The new message is generated for the user whose chat is already present in the chat list. In this scenario, we will follow the steps mentioned below:

    1. Use the getNodeFromList() function implemented in the previous lesson to retrieve a node from the linked list using the id and hashmap.

    2. If the linked list is empty, then set the node as the head of the linked list.

    3. If the linked list is not empty, then add the node to the head of the linked list and update the pointers in such a way that the current node becomes the head of the linked list (most recently used) and the node at the end of the linked list becomes the least recently used. All these operations can be done in O(1)O(1) since we have access to the head of the linked list and the current node.

    4. Finally, update the chat list to be displayed on the HTML web page.

  2. The new message is generated for a new user who is not present in the chat list. In this scenario, we will follow the steps mentioned below:

    1. Create a new node using the createNode() function that we implemented in a previous lesson.

    2. Follow the steps from the previous scenario.

Here's the implementation:

Get hands-on with 1400+ tech skills courses.