Si serializo una lista vinculada a JSON y la almaceno en un archivo de texto
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; } })Puedo leer el archivo y deserializar los datos para recuperar la lista vinculada, pero ¿qué pasa si quiero agregar un nuevo elemento en la lista vinculada? La serialización solo guarda el estado obj.
¿Hay alguna forma de agregar un nuevo elemento a esta lista y volver a serializarlo?
JSON.parse solo puede producir algunos tipos de datos: booleano, número, cadena, null , matriz y objeto simple. No puede producir una instancia de una clase personalizada.
Para facilitar ese proceso, aquí hay algunas ideas:
next referencias de una lista enlazada, ya que su orden define de forma única estos enlaces implícitamente.toJSON , que es llamado por JSON.stringifyArray .fromJSON estático que tome una cadena JSON y devuelva una instancia de lista vinculada para ella.Aquí está eso implementado:
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);