Review a generated recent-document list

from Arrays and linked lists
Node 24 advanced 15 min 4 issues to find

Review this generated collection against its stated task.

Store untrusted document IDs most-recent-first, move a reopened ID to the front without duplicates, enforce a positive limit, support bounds-checked positional reads, and return a most-recent-first snapshot.

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

generated code is illustrative, not from any one model

Open in playground
Report an error