A guide on inserting an element into a serialized linked list using Javascript

Suppose I serialize a linked list into JSON format and save it in a text file

const myList = new SinglyLinkedList();
myList.push('Bonjour');
myList.push('Monde');
myList.push('!');
myList.print();

fs.writeFile('./test.txt', JSON.stringify(myList), err => {
    if (err) {
        console.log(err);
        return;
    }
})

After reading the file and de-serializing the data, how can I add a new element to this linked list and re-serialize it?

Serialization only retains the object's state, so is there a way to update the list with a new element and serialize it again?

Answer №1

JSON.parse has limitations in terms of the data types it can produce, including boolean, number, string, null, array, and plain object. It cannot generate instances of custom classes.

To address this issue, here are some suggestions:

  • There is no need to serialize the next references in a linked list since their order implicitly defines these links.
  • You can serialize a linked list as if it were an array.
  • Implement iterable linked list instances to easily convert them into arrays for serialization.
  • Create a toJSON method that will be called by JSON.stringify.
  • Allow the linked list constructor to accept multiple arguments that are immediately added to the new list, similar to how the Array constructor works.
  • Add a static method fromJSON to create a linked list instance from a JSON string.

This implementation demonstrates the above points:

class SinglyLinkedList {
    static Node = class {
        constructor(value, next=null) {
            this.value = value;
            this.next = next;
        }
    }
    constructor(...values) {
        this.head = this.tail = null;
        for (let value of values) this.push(value);
    }
    push(value) {
        let node = new SinglyLinkedList.Node(value);
        if (this.tail) {
            this.tail = this.tail.next = node;
        } else {
            this.head = this.tail = node;
        }
    }
    * [Symbol.iterator]() {
        for (let node = this.head; node; node = node.next) {
            yield node.value;
        }
    }
    toJSON() {
        return [...this];
    }
    static fromJSON(json) {
        return new this(...JSON.parse(json));
    }
}

// Demo
// 1. Constructor can accept values to be added to the list
const list = new SinglyLinkedList('Hello', 'World', '!');

// 2. A linked list can be iterated, so no specific print method is needed
console.log(...list);

// 3. JSON.stringify will call toJSON method
let serialized = JSON.stringify(list);
console.log(serialized);

// 4. fromJSON can be used to create a linked list instance from Array-like JSON
let restored = SinglyLinkedList.fromJSON(serialized);

// Again, iteration can be used for printing
console.log(...restored);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When is the best time to access user credentials in the FirebaseUI authentication process?

Referring to a provided example on using firebase authentication with Next.js from the Next.js github, I have noticed that many projects I have studied incorporate createUserWithEmailAndPassword at some point. This function allows them to utilize user cred ...

Creating custom elements for the header bar in Ionic can easily be accomplished by adding your own unique design elements to the header bar or

I'm a beginner with Ionic and I'm looking to customize the items on the header bar. It appears that the header bar is created by the framework within the ion-nav-bar element. <ion-nav-bar class="bar-positive"> <ion-nav-back-button> ...

CodeIgniter tutorial on dynamically populating the second dropdown based on the selection of the first dropdown menu

I have been working on a task to create two dependent drop-down lists (penalty_type based on vehicle_type). Is there anyone willing to help me with the implementation? Here is my code: This is the Controller code snippet: public function index() { ...

Is there a way to retrieve the current route on a custom 404 page in Next.JS?

I have set up a custom 404 page for my Next.JS application (404.js). I want to display a message stating The route <strong>/not-a-route</strong> does not exist, but when I use Next.js's useRouter() and router.pathname, it incorrectly ident ...

changing the value of a jQuery variable when an event occurs

Currently, I am working on an interactive jQuery experience where I want my character to navigate through multiple rooms. $(document).keydown(function(e) { switch (e.which) { case 39: $("#barry").attr("src", "img/characters/BarryBa ...

What makes a single number a valid JSON format?

$.parseJSON("1") results in 1 being returned. It is surprising that this works without throwing an error because it does not follow the standard JSON format like this: { "firstName": "John" } How is it possible for 1 to be parsed correctly? Is there ...

What method does Node.js use to determine if the initial parameter in a callback function is designated as an error handler?

Recently, I've been delving into the world of Node.js and trying to grasp its error-first callback style. I'm intrigued by how a function discerns whether the first parameter is meant for handling errors or for other purposes, especially conside ...

What are some ways to monitor the movement of elements and activate functions at precise locations?

I am working on a project that involves a #ball element which, when clicked, utilizes jQuery animate to move downwards by 210px. The code I currently have is as follows: $('#ball').click(function() { $(this).animate({ top: '+=2 ...

What steps can be taken to restrict a user's access to a route through URL parameters?

I am currently developing an Express application that generates and exports a document based on the selections made by a user from two dropdown menus. The values selected in the dropdowns are passed as route parameters after the user clicks a button, trigg ...

Display a string of text containing multiple interactive links

I have a table and I want to create an interactive effect where, upon mouseover or click of certain elements, text will appear next to it. This text may contain multiple lines and clickable links within the content. For instance, in the table generated by ...

The ng-repeat directive is limited to functionality only within parent divs that have the id of

Is there a way to make ng-repeat work only in one specific place by defining an id where it should apply? I would like to achieve this functionality from the controller. For example, using something like $(#1).(ng-repeat work) Here is an example: <t ...

Issues with JSON button click on login API web server

I have been working on developing a login app that connects to a web server API. Everything runs smoothly when I compile the files in Android Studio. However, upon running the app on either the emulator or a real Android device, I encounter an issue where ...

Gather numerical values and transform them into dates using AngularJS

My Angularjs project involves 3 scopes for year, month, and day which are retrieved from 3 input boxes. I need to combine them into a date, but the current code inserts the date with an additional 22:00:00 like 2019-06-01 22:00:00.000. How can I insert the ...

Tips for ensuring a controller function only runs once in AngularJS

I have a controller that is being referenced in some HTML. The HTML changes on certain events, causing the controller function code to execute multiple times. The issue lies in a portion of the code that should only be executed once. Shown below is the ...

Using AngularJS to Showcase JSON Array

I am currently working with a .json file that contains information about networks, IP addresses, and zones. I am trying to figure out how to display the "ip" array in my .html file. [ { "network":"net1", "ip":[ "19 ...

React Select value remains unchanged after state modification

I'm facing an issue with a select component that should reset to the "Neutral" state after the user clicks the next button. However, it keeps displaying whatever option the user previously selected. The components are structured as shown below. When t ...

Choose every fourth row in the table

Is there a way to alternate the background colors of selected groups of 4 rows in a table? I want to make one group red and the next group blue. Any suggestions or ideas on how to achieve this? <table> <tr style="background-color: red;"> ...

React Grid by DevExtreme

Does anyone have a solution for adjusting the fontSize of the TableHeaderRow in a DevExtreme React Grid? Here is some code from a specific website () that I've been exploring: import * as React from 'react'; // Other imports... const Ad ...

Sorting JavaScript Objects By Date

My goal is to arrange my array of objects with date values in descending and ascending order. Here is the code I am using: function comp(a, b) { return new Date(a.jsDate) - new Date(b.jsDate); } function compNewestFirst(a, b) { return new Date(b.jsD ...

Changing a collection of values in an object into a designated array shape

I have an object with the following values: const data = { "generalInfo": [{ "title": "title1", "permalink": "www.link.com", "manufacturer": "manufacturer1", "category": [{ "term_id": 3 ...