Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
How to add an item to a serialized linked list in Javascript

If I serialize a linked list to JSON and store it in a text file

const list = new SinglyLinkedList();
list.push('Hello');
list.push('World');
list.push('!');
list.print();

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

I can read the file and de-serialize the data to get back the linked list but what if I want to add a new element in the linked list. Serialization only saves the obj state.

Is there any way by which I can add a new item to this list and serialize it again ?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

JSON.parse can only produce a few data types: boolean, number, string, null, array and plain object. It cannot produce an instance of a custom class.

To ease that process, here are some ideas:

  • It is not necessary to serialise the next references of a linked list, since its order uniquely defines these links implicitly.
  • Serialise a linked list as if it was an array.
  • Make your linked list instances iterable. This way it is easy to turn an instance to an array (and serialise that).
  • Implement the toJSON method, which gets called by JSON.stringify
  • Allow the linked list constructor to take any number of arguments, which get added to the new list immediately. This is much like the Array constructor allows.
  • Implement a static fromJSON method that takes a JSON string and returns a linked list instance for it.

Here is that implemented:

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);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda