Sunday, March 29, 2020

Priority Queue with Typescript



Summary

This post covers development of a Priority Queue with Typescript.  The queue is implemented via a Binary Heap.  Typescript features such as static type-checking and object-oriented concepts such as classes, interfaces and inheritance are utilized.

Design

Implementation

Queue Item Class

  1. export class Item {
  2. priority:number;
  3. value:object;
  4.  
  5. constructor(priority:number, value:object) {
  6. this.priority = priority;
  7. this.value = value;
  8. }
  9. }

Heap Interface

  1. import {Item} from './item';
  2.  
  3. export enum Order {MIN, MAX};
  4. export interface Heap {
  5. insert(item:Item):void;
  6. extract():Item;
  7. peek():Item;
  8. show():void;
  9. size():number;
  10. };

Binary Heap Class - snippets

  1. export class BinaryHeap implements Heap {
  2. private order:Order;
  3. private heap:Item[];

  1. insert(item:Item):void {
  2. this.heap.push(item);
  3. this.siftUp(this.heap.length-1);
  4. };

  1. private siftUp(idx:number):void {
  2. let parent:number;
  3. let sorted:boolean = false;
  4.  
  5. while (!sorted) {
  6. parent = this.getParent(idx)
  7. switch (this.order) {
  8. case Order.MIN: {
  9. if (this.heap[idx].priority < this.heap[parent].priority) {
  10. this.swap(idx, parent);
  11. idx = parent;
  12. }
  13. else {
  14. sorted = true;
  15. }
  16. break;
  17. }
  18. case Order.MAX: {
  19. if (this.heap[idx].priority > this.heap[parent].priority) {
  20. this.swap(idx, parent);
  21. idx = parent;
  22. }
  23. else {
  24. sorted = true;
  25. }
  26. break;
  27. }
  28. default: {
  29. sorted = true;
  30. break;
  31. }
  32. }
  33. }
  34. }

Priority Queue Class

  1. export class PriorityQueue {
  2. heap:BinaryHeap;
  3.  
  4. constructor(items:Item[]){
  5. this.heap = new BinaryHeap(items);
  6. }
  7.  
  8. insert(item:Item):void {
  9. this.heap.insert(item);
  10. }
  11.  
  12. isEmpty():boolean {
  13. return this.heap.size() == 0;
  14. }
  15.  
  16. peek():Item {
  17. return this.heap.peek();
  18. }
  19.  
  20. pull():Item {
  21. return this.heap.extract();
  22. }
  23.  
  24. show():void {
  25. this.heap.show();
  26. }
  27. }

Example

 

  1.  

Source

https://github.com/joeywhelan/PriorityQueue

Copyright ©1993-2024 Joey E Whelan, All rights reserved.