Domanda di colloquio di HyperGuest

A typescript code that represents a queue. You must fix the queue code. The main queue code (all the other files are just using this code) import { Message } from "./Database"; export class Queue { private messages: Message[] constructor() { this.messages = [] } Enqueue = (message: Message) => { this.messages.push(message) } Dequeue = (workerId: number): Message | undefined => { return this.messages.splice(0,1)[0] } Confirm = (workerId: number, messageId: string) => { // This method was empty in the original version } Size = () => { return this.messages.length } }

Risposta di colloquio

Anonimo

1 feb 2026

import { Message } from "./Database"; export class Queue { private messages: Message[]; private inProgressKeys: Set; // Tracks keys currently being handled by workers constructor() { this.messages = []; this.inProgressKeys = new Set(); } Enqueue = (message: Message) => { this.messages.push(message); } Dequeue = (workerId: number): Message | undefined => { // Find the first message whose key is NOT currently being processed const index = this.messages.findIndex(m => !this.inProgressKeys.has(m.key)); if (index !== -1) { // Remove the message from the main queue const message = this.messages.splice(index, 1)[0]; // Lock this specific key so other workers don't grab it this.inProgressKeys.add(message.key); return message; } return undefined; } // The worker calls this after the DB operation is finished Confirm = (workerId: number, messageId: string, messageKey: string) => { // Release the lock so the next message for this key can be processed this.inProgressKeys.delete(messageKey); } Size = () => { return this.messages.length; } }