View : 0

12/04/2026 18:16pm

JS2GO EP.34 Managing Heap and Priority Queue in Go and JavaScript

JS2GO EP.34 Managing Heap and Priority Queue in Go and JavaScript

#JS2GO

#JavaScript

#Go

#Priority Queue

#Heap

When your system needs to prioritize tasks such as Job Queues, Pathfinding (A*), or Recommendation Engines you need a data structure that can efficiently “pick the most important item first.” That’s where Heap and Priority Queue come into play in software development.

 

In this article, we’ll explore the core concepts behind Heap and Priority Queue, demonstrate real-world implementations in both JavaScript and Go, and share best practices for applying them in production-grade systems. 🚀

 

1. Understanding the Heap

 

A Heap is a tree-based data structure that organizes elements based on their priority.
There are two main types of heaps:

  • Min-Heap: The smallest value is always at the top.
  • Max-Heap: The largest value is always at the top.

 

Heaps are widely used in systems that require Priority Scheduling, Shortest Path algorithms (like Dijkstra), and Task Queues that always process the highest-priority tasks first.

 

2. Implementing a Heap in JavaScript

 

JavaScript doesn’t have a built-in Heap data structure, but you can easily implement one using a class — or use a third-party library such as heap-js.

 

🔹 Example: Implementing a Min-Heap in JavaScript

class MinHeap {
  constructor() {
    this.heap = [];
  }

  getParentIndex(i) { return Math.floor((i - 1) / 2); }
  getLeftChildIndex(i) { return 2 * i + 1; }
  getRightChildIndex(i) { return 2 * i + 2; }

  swap(i1, i2) {
    [this.heap[i1], this.heap[i2]] = [this.heap[i2], this.heap[i1]];
  }

  insert(value) {
    this.heap.push(value);
    this.heapifyUp();
  }

  heapifyUp() {
    let index = this.heap.length - 1;
    while (this.getParentIndex(index) >= 0 &&
           this.heap[this.getParentIndex(index)] > this.heap[index]) {
      this.swap(index, this.getParentIndex(index));
      index = this.getParentIndex(index);
    }
  }

  extractMin() {
    if (this.heap.length === 0) return null;
    if (this.heap.length === 1) return this.heap.pop();

    const root = this.heap[0];
    this.heap[0] = this.heap.pop();
    this.heapifyDown(0);
    return root;
  }

  heapifyDown(index) {
    let smallest = index;
    const left = this.getLeftChildIndex(index);
    const right = this.getRightChildIndex(index);

    if (left < this.heap.length && this.heap[left] < this.heap[smallest]) smallest = left;
    if (right < this.heap.length && this.heap[right] < this.heap[smallest]) smallest = right;

    if (smallest !== index) {
      this.swap(index, smallest);
      this.heapifyDown(smallest);
    }
  }
}

// Example usage
const minHeap = new MinHeap();
minHeap.insert(5);
minHeap.insert(2);
minHeap.insert(8);
minHeap.insert(1);

console.log(minHeap.extractMin()); // 1
console.log(minHeap.extractMin()); // 2

 

Output:

1
2

 

Advantages:
✅ Easy to understand and customize
✅ Great for algorithm practice and simulations

 

Limitations:
❌ Must be implemented manually
❌ No built-in type safety

 

3. Implementing Heap and Priority Queue in Go

 

Go provides a standard library package called container/heap, which allows you to efficiently manage heap structures with type safety and pointer optimization.

 

🔹 Example: Implementing a Priority Queue in Go

package main

import (
	"container/heap"
	"fmt"
)

// Item represents a task with a specific priority
type Item struct {
	value    string
	priority int
	index    int
}

// PriorityQueue implements heap.Interface
type PriorityQueue []*Item

func (pq PriorityQueue) Len() int { return len(pq) }
func (pq PriorityQueue) Less(i, j int) bool {
	return pq[i].priority < pq[j].priority // Min-Heap
}
func (pq PriorityQueue) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}
func (pq *PriorityQueue) Push(x any) {
	item := x.(*Item)
	item.index = len(*pq)
	*pq = append(*pq, item)
}
func (pq *PriorityQueue) Pop() any {
	old := *pq
	n := len(old)
	item := old[n-1]
	*pq = old[0 : n-1]
	return item
}

func main() {
	pq := make(PriorityQueue, 0)
	heap.Init(&pq)

	heap.Push(&pq, &Item{value: "Job A", priority: 3})
	heap.Push(&pq, &Item{value: "Job B", priority: 1})
	heap.Push(&pq, &Item{value: "Job C", priority: 2})

	for pq.Len() > 0 {
		item := heap.Pop(&pq).(*Item)
		fmt.Printf("%s (priority %d)\n", item.value, item.priority)
	}
}

 

Output:

Job B (priority 1)
Job C (priority 2)
Job A (priority 3)

 

Advantages of Go:
✅ Built-in support via container/heap
✅ Type-safe and memory efficient
✅ Ideal for production systems such as job schedulers or background workers

 

4. Best Practices

 

Use CaseRecommended LanguageBest Practice
Algorithm SimulationJavaScriptImplement manually to understand heap mechanics
Production Queue SystemGoUse container/heap for performance and stability
Pathfinding (A*, Dijkstra)BothUse Priority Queue to compute the shortest path
Task Scheduling / Job ManagementGoUtilize Priority Queue for efficient task prioritization

 

5. Comparison: Heap and Priority Queue

 

FeatureJavaScriptGo
Built-in Support❌ None✅ Yes (container/heap)
Type Safety❌ No✅ Yes
PerformanceModerateHigh
Best ForAlgorithm learning, simulationProduction systems, job scheduling
Ease of UseSimple to implementRequires interface implementation

 


 

Conclusion

 

Understanding Heap and Priority Queue enables developers to build systems that can efficiently manage task prioritization whether you’re building a Job Queue, Pathfinding Engine, or Task Scheduler.

  • 💡 If you want flexibility and a deeper understanding of algorithms → choose JavaScript
  • ⚙️ If you need performance and production reliability → choose Go

 

Next Episode

 

In EP.35 of the JS2GO series, we’ll explore Sorting Algorithms in JavaScript and Go, comparing techniques like Bubble Sort, Merge Sort, Quick Sort, and Go’s built-in sort package to see which language performs better and how to apply them effectively in real-world systems. 🔥

 

Read more

🔵 Facebook: Superdev Academy

🔴 YouTube: Superdev Academy

📸 Instagram: Superdev Academy

🎬 TikTok: https://www.tiktok.com/@superdevacademy?lang=th-TH

🌐 Website: https://www.superdevacademy.com/en