Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

164
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda