如何将项目添加到 Javascript 中的序列化链表

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

如果我将链表序列化为 JSON 并将其存储在文本文件中

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

我可以读取文件并反序列化数据以取回链表,但是如果我想在链表中添加新元素怎么办。序列化只保存obj状态

有什么方法可以将新项目添加到此列表并再次序列化吗?

JSON.parse 只能产生几种数据类型:布尔值、数字、字符串、null、数组和普通对象。它无法生成自定义 class.

的实例

为了简化这个过程,这里有一些想法:

  • 没有必要序列化链接列表的 next 引用,因为它的顺序唯一地隐式定义了这些链接。
  • 像数组一样序列化链表。
  • 使您的链表实例可迭代。这样就很容易将实例转换为数组(并序列化 that)。
  • 实施 toJSON 方法,该方法由 JSON.stringify
  • 调用
  • 允许链表构造函数接受任意数量的参数,这些参数会立即添加到新列表中。这很像 Array 构造函数允许的。
  • 实现一个静态 fromJSON 方法,它接受一个 JSON 字符串和 returns 它的链表实例。

这是实现的:

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