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 ?
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:
next references of a linked list, since its order uniquely defines these links implicitly.toJSON method, which gets called by JSON.stringifyArray constructor allows.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);