Priority Queue With Dead Letter

Implement a priority queue with dead letter handling for failed messages after max retries.

TypescriptData Fetching

Code

typescriptsnippet
1 line
interface Job<T>{data:T;priority:number;attempts:number;}export class PriorityDLQueue<T>{private queue:Job<T>[]=[];private dead:Job<T>[]=[];constructor(private maxRetries=3){}enqueue(data:T,priority=0):void{this.queue.push({data,priority,attempts:0});this.queue.sort((a,b)=>b.priority-a.priority);}dequeue():Job<T>|undefined{return this.queue.shift();}markFailed(job:Job<T>):void{job.attempts++;if(job.attempts>=this.maxRetries)this.dead.push(job);else this.queue.push(job),this.queue.sort((a,b)=>b.priority-a.priority);}getDeadLetter():Job<T>[]{return[...this.dead];}}

How it works

Count the class PriorityDLQueue as the entire surface area of Priority Queue With Dead Letter.

Putting it to use

Import PriorityDLQueue from the file and call it — the rest of the code is implementation detail.

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free.