我正在自己构建一个链接列表。我试图在构造函数中将生成器分配为键/值 WeakMap 的值。这_iterator
是一个 WeakMap,因为它是一个私有成员,我想用它来对我的数据结构进行简单的迭代,但我不想让生成器在外部可见,否则我会破坏抽象。但我有错误SyntaxError: missing ( before formal parameters
。问题是什么?
class Node{
constructor(value){
this.value = value;
this.next = null;
}
}
//IIFE function that return the class.
const SingleLinkedList = (() => { //Here use IIFE to create a new block scope for private variables
let _counts = new WeakMap();
let _head = new WeakMap();
let _tail = new WeakMap();
let _iterator = new WeakMap();
class SingleLinkedList {
constructor() {
_counts.set(this, 0);
_head.set(this, null);
_tail.set(this, null);
let instance = this;//closure
_iterator.set(this,(function* [Symbol.iterator](){
let n=_head.get(instance);
while(n){
yield n;
n = n.next;
}
}));
}
get counts() { //read only get accessor property
return _counts.get(this);
}
isEmpty() {
return !this.counts; //or return !_head.get(this)
}
//insert a new Node (in tail) with the desired value
push(value) {
let n = new Node(value);
if (this.isEmpty())
_head.set(this, n);
else {
let tail = _tail.get(this); //tail is a pointer to the node-tail
tail.next = n; //old tail-node will point to new node
}
//the following instructions are common to both the cases.
_tail.set(this, n); //set new tail
_counts.set(this, this.counts+1); //increment item counter
return this; //to allow multiple push call
}
//Generator to return the values
*[Symbol.iterator](){
let n = _head.get(this);
while(n){
yield n.value;
n=n.next;
}
}
//the the values of each node
print() {
let output = "";
for(let el of this)
output += `${el} `;
console.log(output);
}
}
return SingleLinkedList;
})();
let myLinkedList = new SingleLinkedList();
myLinkedList.push(3);
myLinkedList.push(5);
myLinkedList.print();
/*for(let x of myLinkedList)
console.log(x);*/