根据给定任务审查这个生成的集合。
按最近优先顺序存储不可信文档 ID,重新打开时把 ID 移到头部且不重复,执行正数容量限制,支持带边界检查的按位置读取,并返回最近优先快照。
JavaScript
class RecentDocuments {
constructor(limit) {
this.limit = limit;
this.byId = {};
this.head = null;
}
open(id) {
if (this.byId[id]) return;
const node = { id, next: this.head };
this.byId[id] = node;
this.head = node;
}
at(index) {
let node = this.head;
for (let step = 0; step <= index; step += 1) node = node.next;
return node.id;
}
toArray() {
const result = [];
for (let node = this.head; node; node = node.next) {
result.unshift(node.id);
}
return result;
}
}
生成代码仅作示例,不代表任何特定模型