<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mojtaba Sabouri on Medium]]></title>
        <description><![CDATA[Stories by Mojtaba Sabouri on Medium]]></description>
        <link>https://medium.com/@sabouri.dev?source=rss-d5474aae2d3a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LsAmRXg-iLstcx9RSYVpCQ.jpeg</url>
            <title>Stories by Mojtaba Sabouri on Medium</title>
            <link>https://medium.com/@sabouri.dev?source=rss-d5474aae2d3a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 12:53:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sabouri.dev/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Ref-Snapshot Pattern: 3 Hooks from Telegram’s Codebase That Solve React’s Stale Closure Problem]]></title>
            <link>https://medium.com/@sabouri.dev/the-ref-snapshot-pattern-3-hooks-from-telegrams-codebase-that-solve-react-s-stale-closure-problem-ec353fe43bca?source=rss-d5474aae2d3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec353fe43bca</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Mojtaba Sabouri]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 05:30:06 GMT</pubDate>
            <atom:updated>2026-06-23T05:30:06.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_MhSfFNwxd0WJK20ruu9QA.png" /></figure><h4>How a 10-line pattern from one of the world’s most-used messengers fixes what useCallback quietly gets wrong</h4><p>I was reading through Telegram Web’s open-source codebase, not looking for anything in particular. Then I found three hooks — ten lines each, no dependencies, no magic. They solved problems I had been working on for months.</p><p>All three are built on the same idea. One ref. One useLayoutEffect with no dependency array. Read the ref during render, update it after. That’s it. Applied three different ways, it handles three different gaps in React’s built-in toolkit.</p><h3>The Problem React Doesn’t Tell You About</h3><p>React’s mental model is clean: render is a pure function of props and state, effects handle side effects, and hooks compose behaviour. The documentation is careful and well-written.</p><p>What it doesn’t explain clearly is what happens when you need <em>history</em> — when your component needs to know what a value <em>was</em>, not just what it <em>is</em>.</p><p>useState gives you the current value. useRef gives you a mutable container. useEffect runs after render. None of them natively gives you “what was this value on the previous render?” And that gap, once you know it exists, shows up constantly in real production codebases.</p><h3>The Foundation: usePrevious</h3><p>The simplest of the three. It captures the previous render’s value of anything — state, props, or a derived value.</p><pre>import { useLayoutEffect, useRef } from &#39;react&#39;<br><br>export default function usePrevious&lt;T&gt;(value: T): T | undefined {<br>  const ref = useRef&lt;T | undefined&gt;(undefined)<br>  const prev = ref.current // read before the update<br>  useLayoutEffect(() =&gt; {<br>    ref.current = value   // update after render, for next time<br>  })<br>  return prev<br>}</pre><p>The mechanism is subtle but precise. ref.current is read during the render phase — before any effects fire — so prev captures what the ref held at the <em>end</em> of the previous render. Then useLayoutEffect (with no dependency array, so it runs every render) updates the ref for next time.</p><p>useLayoutEffect rather than useEffect matters here. Layout effects fire synchronously after DOM mutations but before paint. This means the update happens in the same frame, so nothing can observe a stale value between renders.</p><p>Usage looks like this:</p><pre>function ConversationHeader({ conversationId }: Props) {<br>  const prevConversationId = usePrevious(conversationId)<br><br>  useEffect(() =&gt; {<br>    if (prevConversationId &amp;&amp; prevConversationId !== conversationId) {<br>      // conversation changed — clear scroll position, reset unread count, etc.<br>      resetConversationState(prevConversationId)<br>    }<br>  }, [conversationId])<br>}</pre><p>Without usePrevious, you’d need to track the previous value yourself with a ref and imperative update logic scattered across effects. This encapsulates the pattern cleanly.</p><h3>Building on It: useEffectWithPrevDeps</h3><p>Once you have usePrevious, a natural extension appears: what if an effect needs to <em>compare</em> old and new values, not just react to the current ones?</p><pre>import { useEffect } from &#39;react&#39;<br>import usePrevious from &#39;./usePrevious&#39;<br><br>export default function useEffectWithPrevDeps&lt;T extends readonly unknown[]&gt;(<br>  cb: (prevDeps: T | readonly []) =&gt; void,<br>  deps: T,<br>): void {<br>  const prevDeps = usePrevious(deps)<br>  // eslint-disable-next-line react-hooks/exhaustive-deps<br>  useEffect(() =&gt; cb(prevDeps ?? []), deps)<br>}</pre><p>The callback receives the previous values of the dependency array as an argument, alongside the current ones being accessible via closure. This makes transition logic — “what changed and from what to what” — straightforward to express.</p><pre>useEffectWithPrevDeps(<br>  ([prevIsOpen]) =&gt; {<br>    if (prevIsOpen === true &amp;&amp; !isOpen) {<br>      // panel just closed — run exit animation, save draft, etc.<br>      handlePanelClose()<br>    }<br>  },<br>  [isOpen] as const,<br>)</pre><p>One honest caveat: this hook uses eslint-disable on react-hooks/exhaustive-deps. It opts out of the linter’s safety net. The pattern is correct — it works as intended — but it requires the developer to be disciplined about what goes in the deps array. It doesn’t remove the responsibility for correctness; it just removes the automated check.</p><p>Use it for transition-aware effects. Don’t use it to smuggle variables out of the deps array as a shortcut.</p><h3>The Real Gem: useLastCallback</h3><p>This is the one that earns the most use. It solves the most common friction point in memoized component trees: the tension between <em>stable function reference</em> and <em>fresh closure values</em>.</p><pre>import { useCallback, useLayoutEffect, useRef } from &#39;react&#39;<br>import type { AnyFunction } from &#39;@lib/types&#39;<br><br>export default function useLastCallback&lt;T extends AnyFunction&gt;(fn: T): T {<br>  const ref = useRef(fn)<br>  useLayoutEffect(() =&gt; {<br>    ref.current = fn<br>  })<br>  return useCallback((...args: Parameters&lt;T&gt;) =&gt; ref.current(...args), []) as T<br>}</pre><p>To understand why this exists, consider the standard approach to passing callbacks to memoized children:</p><pre>// Standard approach — broken in subtle ways<br>const handleSubmit = useCallback((message: string) =&gt; {<br>  sendMessage(message, currentUser, activeConversation) // uses current state<br>}, [currentUser, activeConversation]) // deps change → new reference → child re-renders</pre><p>React.memo stops re-renders when props haven’t changed. But if handleSubmit is in deps and those deps change, useCallback produces a new function reference. A new reference triggers a re-render in the memoized child even though the behaviour of the callback from the child’s perspective is identical.</p><p>The common “fix” — removing deps from useCallback — just creates a stale closure. The function stabilizes, but it reads the state from when it was created, not when it’s called.</p><p>useLastCallback breaks this tradeoff. The ref is always updated to the latest version of fn via useLayoutEffect. The returned useCallback wrapper has a stable reference (empty deps array, never changes). When the wrapper is called, it delegates to ref.current — which is always the latest version of the function, with the latest closure values.</p><pre>const handleSubmit = useLastCallback((message: string) =&gt; {<br>  sendMessage(message, currentUser, activeConversation)<br>  // reads current state at call time, not at creation time<br>})<br><br>// handleSubmit&#39;s reference never changes → memoized child never re-renders unnecessarily</pre><p>One important boundary: don’t use useLastCallback for values that need to be captured at render time for rendering itself. The ref updates asynchronously relative to the render cycle. If you use this for a value that drives what gets rendered, you introduce a subtle timing issue. It’s for event handlers and callbacks — things called in response to user interaction, not things read during render.</p><h3>React’s own answer — and why it’s not the same</h3><p>React introduced useEffectEvent with the same underlying mechanism: store the latest function in a ref, read from it at call time. But the contract is different.</p><p>useEffectEvent is scoped strictly to inside useEffect — React explicitly blocks you from passing it to other components. Its job is to let a value participate in an effect without becoming a reactive dependency.</p><p>useLastCallback solves the opposite problem: a stable reference you can hand to a memoized child. The restriction that makes useEffectEvent safe is exactly what makes it useless here.</p><p>Same pattern. Different contract.</p><h3>The Pattern They Share</h3><p>All three hooks use the same mechanism:</p><pre>const ref = useRef(initialValue)<br>const snapshot = ref.current  // read during render (before effects)<br>useLayoutEffect(() =&gt; {<br>  ref.current = latestValue   // update after render (before paint)<br>})</pre><p>The ref is a stable container. Reading it during render gives you the last render’s value. Updating it in useLayoutEffect ensures it’s current for anything that runs after. The choice of useLayoutEffect over useEffect is deliberate in all three — it keeps the update in the same frame, avoiding any window where something could observe stale data.</p><p>Telegram built three different tools on this foundation because three different situations call for it: tracking previous values, writing transition-aware effects, and keeping callbacks stable in memoized trees. The underlying pattern is one. The applications are distinct.</p><h3>When to Reach for Each</h3><p>usePrevious — when you need to compare the current value of something to what it was last render. Useful for detecting transitions: conversation changed, modal just opened, user went from unauthenticated to authenticated.</p><p>useEffectWithPrevDeps — when an effect’s logic depends on <em>what changed</em>, not just <em>that something changed</em>. Useful for animation triggers, cleanup that needs context about the previous state, or any effect where “from X to Y” is different from “from Y to X.”</p><p>useLastCallback — when you pass callbacks to memoized children and want neither stale closures nor unnecessary re-renders. This one belongs in nearly every component tree with React.memo in it.</p><p>The three hooks are each under 15 lines. They have no dependencies. They require no library. And they solve problems that become expensive at scale — in a codebase behind one of the most widely used messaging platforms in the world, the choice of this pattern over the alternatives was clearly intentional.</p><p>The pattern is simple enough that once you see it, you recognise the problem everywhere it applies.</p><p><em>If you found this useful, the next article goes deeper on useLastCallback specifically — including the full mental model of why useCallback alone isn’t enough and when to reach for this pattern versus alternatives.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec353fe43bca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Priority Queue from Scratch in TypeScript]]></title>
            <link>https://medium.com/@sabouri.dev/building-a-priority-queue-from-scratch-in-typescript-f2b7ae866bfa?source=rss-d5474aae2d3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2b7ae866bfa</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[priority-queue]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mojtaba Sabouri]]></dc:creator>
            <pubDate>Mon, 18 May 2026 20:36:00 GMT</pubDate>
            <atom:updated>2026-05-18T20:36:00.430Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fri66GemZ_9O0K-xNbhgEw.png" /></figure><h3>Building a Priority Queue from Scratch in TypeScript</h3><p><em>Part 3 of 3 — </em>Understanding Priority Queues in TypeScript</p><p>This is the article I actually wanted to find when I started building my TypeScript package. Not just the code. Not just the explanation. Both — together, line by line, so you walk away actually understanding what you built and why every decision was made.</p><p>In Part 1, we covered what a priority queue is and where it’s used. In Part 2, we derived the math behind heaps from first principles. Now we build the real thing.</p><p>By the end of this article, you’ll have a fully working, generic, type-safe PriorityQueue&lt;T&gt; class in TypeScript — something you can drop straight into a real project. Let’s go.</p><h3>What We’re Building</h3><p>Here’s a quick overview of what the final class will support:</p><pre>const pq = new PriorityQueue&lt;number&gt;((a, b) =&gt; a - b); // min-heap<br><br>pq.enqueue(5);<br>pq.enqueue(1);<br>pq.enqueue(3);<br><br>pq.peek();    // 1  (doesn&#39;t remove)<br>pq.dequeue(); // 1  (removes and returns)<br>pq.size;      // 2<br>pq.isEmpty(); // false</pre><p>And for objects:</p><pre>interface Task {<br>  name: string;<br>  urgency: number;<br>}<br><br>const tasks = new PriorityQueue&lt;Task&gt;((a, b) =&gt; b.urgency - a.urgency); // max-heap by urgency<br><br>tasks.enqueue({ name: &quot;Send email&quot;, urgency: 2 });<br>tasks.enqueue({ name: &quot;Fix crash&quot;, urgency: 10 });<br>tasks.enqueue({ name: &quot;Update docs&quot;, urgency: 1 });<br><br>tasks.dequeue(); // { name: &quot;Fix crash&quot;, urgency: 10 }</pre><h3>Step 1 — The Comparator Type</h3><p>Before we write the class itself, we need to define one thing: how does the queue decide which element has higher priority?</p><p>The answer is a <strong>comparator function</strong>. This is the same pattern used by Array.prototype.sort(), so it&#39;ll feel familiar.</p><pre>export type Comparator&lt;T&gt; = (a: T, b: T) =&gt; number;</pre><p>The rules are simple:</p><ul><li>Returns a <strong>negative number</strong> → a has higher priority than b</li><li>Returns <strong>zero</strong> → a and b have equal priority</li><li>Returns a <strong>positive number</strong> → b has higher priority than a</li></ul><p>This single function is what makes our implementation flexible enough to act as either a min-heap or a max-heap, for any type of data:</p><pre>// Min-heap (smallest number = highest priority)<br>(a, b) =&gt; a - b<br><br>// Max-heap (largest number = highest priority)<br>(a, b) =&gt; b - a<br><br>// Max-heap by object property<br>(a, b) =&gt; b.urgency - a.urgency</pre><p>By putting this decision in the caller’s hands, we don’t have to hardcode anything. One class handles everything.</p><h3>Step 2 — The Class Skeleton</h3><p>Let’s set up the basic structure:</p><pre>export class PriorityQueue&lt;T&gt; {<br>  private heap: T[] = [];<br>  private comparator: Comparator&lt;T&gt;;<br><br>  constructor(comparator: Comparator&lt;T&gt;) {<br>    this.comparator = comparator;<br>  }<br>}</pre><p>A few things to notice:</p><ul><li>&lt;T&gt; makes this class <strong>generic</strong> — it works with numbers, strings, objects, anything.</li><li>private heap: T[] is our underlying array. The tree lives here, flattened into a list using the index formulas from Part 2.</li><li>private comparator stores the user&#39;s priority function. We keep both fields private so nothing outside the class can mess with the internal state directly.</li></ul><h3>Step 3 — The Simple Public Methods</h3><p>These four methods are all O(1) and straightforward:</p><pre>// How many elements are in the queue?<br>public get size(): number {<br>  return this.heap.length;<br>}<br><br>// Is the queue empty?<br>public isEmpty(): boolean {<br>  return this.heap.length === 0;<br>}<br><br>// What&#39;s the highest priority element? (without removing it)<br>public peek(): T | undefined {<br>  return this.heap[0];<br>}<br><br>// Remove all elements<br>public clear(): void {<br>  this.heap = [];<br>}</pre><p>peek() returns T | undefined rather than just T because the queue might be empty. Returning undefined is safer than throwing an error for a simple read operation — the caller can decide how to handle it.</p><h3>Step 4 — The Index Helper Methods</h3><p>These three private methods are the navigation tools for our array-based tree. They come directly from the formulas we proved in Part 2:</p><pre>private getParentIndex(i: number): number {<br>  return Math.floor((i - 1) / 2);<br>}<br><br>private getLeftChildIndex(i: number): number {<br>  return 2 * i + 1;<br>}<br><br>private getRightChildIndex(i: number): number {<br>  return 2 * i + 2;<br>}</pre><p>And one more utility — swapping two elements in the array:</p><pre>private swap(i: number, j: number): void {<br>  [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];<br>}</pre><p>This uses JavaScript’s destructuring assignment to swap in one line without a temporary variable. Clean and readable.</p><h3>Step 5 — Enqueue (Add an Element)</h3><p>Adding an element has two steps:</p><ol><li>Place it at the <strong>end</strong> of the array (the bottom of the tree)</li><li><strong>Sift it up</strong> until the heap property is restored</li></ol><pre>public enqueue(element: T): void {<br>  this.heap.push(element);<br>  this.siftUp();<br>}</pre><p>Simple on the surface. The real work happens in siftUp():</p><pre>private siftUp(): void {<br>  let current = this.heap.length - 1; // Start at the newly added element<br><br>  while (current &gt; 0) {<br>    const parent = this.getParentIndex(current);<br><br>    // If the parent already has higher or equal priority, we&#39;re done.<br>    // comparator &lt;= 0 means parent has higher or equal priority.<br>    if (this.comparator(this.heap[parent], this.heap[current]) &lt;= 0) {<br>      break;<br>    }<br><br>    // Parent has lower priority — swap and keep climbing<br>    this.swap(current, parent);<br>    current = parent;<br>  }<br>}</pre><p>Let’s walk through this with a concrete example.</p><p>We have a min-heap: [1, 3, 2]. We enqueue 0.</p><pre>Array after push: [1, 3, 2, 0]<br><br>Step 1: current = 3 (the new element, value 0)<br>        parent  = floor((3-1)/2) = 1 (value 3)<br>        comparator(3, 0) = 3 - 0 = 3 → positive → parent has LOWER priority<br>        → swap indices 3 and 1<br>        Array: [1, 0, 2, 3]<br><br>Step 2: current = 1 (value 0)<br>        parent  = floor((1-1)/2) = 0 (value 1)<br>        comparator(1, 0) = 1 - 0 = 1 → positive → parent has LOWER priority<br>        → swap indices 1 and 0<br>        Array: [0, 1, 2, 3]<br><br>Step 3: current = 0<br>        Loop condition: 0 &gt; 0 is false → stop</pre><p>Final heap: [0, 1, 2, 3]. The 0 has correctly bubbled all the way to the top. ✅</p><p>Each loop iteration moves one level up the tree. Since the tree height is log₂(n), this is <strong>O(log n)</strong> in the worst case.</p><h3>Step 6 — Dequeue (Remove the Highest Priority Element)</h3><p>Each loop iteration moves one level up the tree. Since the tree height is log₂(n), this is <strong>O(log n)</strong> in the worst case.Step 6 — Dequeue (Remove the Highest Priority Element)</p><p>This is the most important operation. Removing the root (top element) has three steps:</p><ol><li>Save the root — that’s what we’ll return</li><li>Move the <strong>last element</strong> to the root position</li><li><strong>Sift it down</strong> until the heap property is restored</li></ol><pre>public dequeue(): T | undefined {<br>  if (this.isEmpty()) {<br>    return undefined;<br>  }<br><br>  const root = this.heap[0];         // Save the top element<br>  const last = this.heap.pop()!;     // Remove the last element<br><br>  if (!this.isEmpty()) {<br>    this.heap[0] = last;             // Put the last element at the root<br>    this.siftDown(0);                // Push it down to its correct position<br>  }<br><br>  return root;<br>}</pre><p>Why move the last element to the root instead of just removing the root and shifting everything? Because shifting would cost O(n). Moving the last element costs O(1), and then sifting down costs O(log n). Much better.</p><p>Now the siftDown() method:</p><pre>private siftDown(start: number): void {<br>  let current = start;<br>  const length = this.heap.length;<br><br>  while (true) {<br>    const left  = this.getLeftChildIndex(current);<br>    const right = this.getRightChildIndex(current);<br>    let highest = current; // Assume current has the highest priority<br><br>    // Is the left child higher priority than current best?<br>    if (left &lt; length &amp;&amp; this.comparator(this.heap[left], this.heap[highest]) &lt; 0) {<br>      highest = left;<br>    }<br><br>    // Is the right child higher priority than current best?<br>    if (right &lt; length &amp;&amp; this.comparator(this.heap[right], this.heap[highest]) &lt; 0) {<br>      highest = right;<br>    }<br><br>    // If neither child beat the current element, we&#39;re in the right spot<br>    if (highest === current) {<br>      break;<br>    }<br><br>    // Otherwise, swap with the highest-priority child and continue downward<br>    this.swap(current, highest);<br>    current = highest;<br>  }<br>}</pre><p>The highest variable is the key insight here. We don&#39;t just compare with one child — we need to find which of the three candidates (current element, left child, right child) has the highest priority, and if it&#39;s not the current element, we swap downward with the best child.</p><p><strong>Example — dequeue from min-heap </strong><strong>[1, 3, 2, 7, 4, 5]:</strong></p><pre>Step 1: Save root → 1. Move last element (5) to root.<br>        Array: [5, 3, 2, 7, 4]<br><br>Step 2: current = 0 (value 5)<br>        left = 1 (value 3) → 3 &lt; 5 → highest = 1<br>        right = 2 (value 2) → 2 &lt; 3 → highest = 2<br>        Swap 0 and 2 → [2, 3, 5, 7, 4]<br><br>Step 3: current = 2 (value 5)<br>        left = 5 → out of bounds<br>        right = 6 → out of bounds<br>        highest = 2 (current) → break<br><br>Final: [2, 3, 5, 7, 4]<br>Return: 1 ✅</pre><h3>Step 7 — fromArray (Bonus: Build a Heap in O(n))</h3><p>There’s a smarter way to build a heap from an existing array than inserting elements one by one (which would be O(n log n)).</p><p>It’s called <strong>heapify</strong>, and it runs in <strong>O(n)</strong>. The idea: start from the last non-leaf node and sift each one down. By the time you reach the root, the entire array is a valid heap.</p><pre>public static fromArray&lt;U&gt;(elements: U[], comparator: Comparator&lt;U&gt;): PriorityQueue&lt;U&gt; {<br>  const pq = new PriorityQueue&lt;U&gt;(comparator);<br>  pq.heap = [...elements]; // copy the array — don&#39;t mutate the original<br><br>  // Last non-leaf node is at floor((n - 2) / 2)<br>  const lastNonLeaf = Math.floor((pq.heap.length - 2) / 2);<br><br>  // Sift down every non-leaf node, from bottom to top<br>  for (let i = lastNonLeaf; i &gt;= 0; i--) {<br>    pq.siftDown(i);<br>  }<br><br>  return pq;<br>}</pre><p>Why start from the last non-leaf and go upward? Because leaf nodes are already valid heaps on their own (they have no children to violate the property). We only need to fix the internal nodes.</p><pre>// Instead of this (O(n log n)):<br>const pq = new PriorityQueue&lt;number&gt;((a, b) =&gt; a - b);<br>[5, 3, 8, 1, 4].forEach(n =&gt; pq.enqueue(n));<br><br>// Do this (O(n)):<br>const pq = PriorityQueue.fromArray([5, 3, 8, 1, 4], (a, b) =&gt; a - b);</pre><h3>The Complete Implementation</h3><p>Here’s the entire class together, clean and ready to copy:</p><pre>export type Comparator&lt;T&gt; = (a: T, b: T) =&gt; number;<br><br>export class PriorityQueue&lt;T&gt; {<br>  private heap: T[] = [];<br>  private comparator: Comparator&lt;T&gt;;<br><br>  constructor(comparator: Comparator&lt;T&gt;) {<br>    this.comparator = comparator;<br>  }<br><br>  public get size(): number {<br>    return this.heap.length;<br>  }<br><br>  public isEmpty(): boolean {<br>    return this.heap.length === 0;<br>  }<br><br>  public peek(): T | undefined {<br>    return this.heap[0];<br>  }<br><br>  public clear(): void {<br>    this.heap = [];<br>  }<br><br>  public enqueue(element: T): void {<br>    this.heap.push(element);<br>    this.siftUp();<br>  }<br><br>  public dequeue(): T | undefined {<br>    if (this.isEmpty()) return undefined;<br><br>    const root = this.heap[0];<br>    const last = this.heap.pop()!;<br><br>    if (!this.isEmpty()) {<br>      this.heap[0] = last;<br>      this.siftDown(0);<br>    }<br><br>    return root;<br>  }<br><br>  public static fromArray&lt;U&gt;(elements: U[], comparator: Comparator&lt;U&gt;): PriorityQueue&lt;U&gt; {<br>    const pq = new PriorityQueue&lt;U&gt;(comparator);<br>    pq.heap = [...elements];<br>    const lastNonLeaf = Math.floor((pq.heap.length - 2) / 2);<br>    for (let i = lastNonLeaf; i &gt;= 0; i--) {<br>      pq.siftDown(i);<br>    }<br>    return pq;<br>  }<br><br>  private siftUp(): void {<br>    let current = this.heap.length - 1;<br>    while (current &gt; 0) {<br>      const parent = this.getParentIndex(current);<br>      if (this.comparator(this.heap[parent], this.heap[current]) &lt;= 0) break;<br>      this.swap(current, parent);<br>      current = parent;<br>    }<br>  }<br><br>  private siftDown(start: number): void {<br>    let current = start;<br>    const length = this.heap.length;<br>    while (true) {<br>      const left  = this.getLeftChildIndex(current);<br>      const right = this.getRightChildIndex(current);<br>      let highest = current;<br>      if (left  &lt; length &amp;&amp; this.comparator(this.heap[left],  this.heap[highest]) &lt; 0) highest = left;<br>      if (right &lt; length &amp;&amp; this.comparator(this.heap[right], this.heap[highest]) &lt; 0) highest = right;<br>      if (highest === current) break;<br>      this.swap(current, highest);<br>      current = highest;<br>    }<br>  }<br><br>  private getParentIndex(i: number): number { return Math.floor((i - 1) / 2); }<br>  private getLeftChildIndex(i: number): number { return 2 * i + 1; }<br>  private getRightChildIndex(i: number): number { return 2 * i + 2; }<br><br>  private swap(i: number, j: number): void {<br>    [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]];<br>  }<br>}</pre><h3>Complexity Summary</h3><pre>enqueue   → O(log n)  siftUp traverses tree height<br>dequeue   → O(log n)  siftDown traverses tree height<br>peek      → O(1)      always at index 0<br>size      → O(1)      just array length<br>isEmpty   → O(1)      just array length check<br>fromArray → O(n)      heapify algorithm</pre><p>Space complexity is <strong>O(n)</strong> — we store exactly the elements you give us.</p><h3>Quick Recap</h3><p>Here’s what we built and why each piece matters:</p><ul><li><strong>Comparator function</strong> — makes the queue flexible for any type, any priority direction</li><li><strong>Array-based heap</strong> — no tree node objects needed, just index math</li><li><strong>siftUp</strong> — restores heap order after every enqueue, O(log n)</li><li><strong>siftDown</strong> — restores heap order after every dequeue, O(log n)</li><li><strong>fromArray</strong> — builds a valid heap from existing data in O(n) using heapify</li><li><strong>Generic </strong><strong>&lt;T&gt;</strong> — fully type-safe, works with any TypeScript type</li></ul><h3>What’s Next for This Code?</h3><p>If you want to take this further, here are some directions worth exploring:</p><ul><li><strong>updatePriority()</strong> — changing an element&#39;s priority after it&#39;s been added. This requires storing an index map alongside the heap to find elements in O(1) rather than O(n).</li><li><strong>remove(element)</strong> — removing an arbitrary element. Same challenge as above — straightforward with an index map.</li><li><strong>merge(otherQueue)</strong> — combining two priority queues. Standard binary heaps don&#39;t do this efficiently; you&#39;d need a different structure, like a Fibonacci heap for O(log n) merge.</li></ul><p>For most use cases though, what we’ve built here is exactly what you need.</p><p><em>This is Part 3 of a 3-part series on Priority Queues.<br></em> <em>← Part 1: </em><a href="https://medium.com/@sabouri.dev/what-is-a-queue-and-why-does-priority-matter-69936d3c7b9c"><em>What is a Queue, and Why Does Priority Matter?</em></a><em><br></em> <em>← Part 2: </em><a href="https://medium.com/@sabouri.dev/heaps-explained-the-math-behind-priority-queues-d43c6746f0d6"><em>Heaps Explained — The Math Behind Priority Queues</em></a></p><h3>✦ Optional Reading — Writing Tests for Your Priority Queue</h3><p><em>This section walks through how to test every behaviour we built, using </em><strong><em>Vitest</em></strong><em> (works the same with Jest if you prefer).</em></p><h3>Setup</h3><pre>npm install -D vitest</pre><pre>// package.json<br>&quot;scripts&quot;: {<br>  &quot;test&quot;: &quot;vitest&quot;<br>}</pre><p>Create a file: priority-queue.test.ts</p><h3>Test 1 — Basic Min-Heap Ordering</h3><p>The most fundamental test: does dequeue return elements in the right order?</p><pre>import { describe, it, expect } from &#39;vitest&#39;;<br>import { PriorityQueue } from &#39;./priority-queue&#39;;<br><br>describe(&#39;PriorityQueue - min-heap&#39;, () =&gt; {<br>  it(&#39;dequeues elements in ascending order&#39;, () =&gt; {<br>    const pq = new PriorityQueue&lt;number&gt;((a, b) =&gt; a - b);<br>    pq.enqueue(5);<br>    pq.enqueue(1);<br>    pq.enqueue(3);<br>    pq.enqueue(2);<br>    pq.enqueue(4);<br><br>    expect(pq.dequeue()).toBe(1);<br>    expect(pq.dequeue()).toBe(2);<br>    expect(pq.dequeue()).toBe(3);<br>    expect(pq.dequeue()).toBe(4);<br>    expect(pq.dequeue()).toBe(5);<br>  });<br>});</pre><h3>Test 2 — Max-Heap Ordering</h3><p>Same test, reversed comparator:</p><pre>it(&#39;dequeues elements in descending order for max-heap&#39;, () =&gt; {<br>  const pq = new PriorityQueue&lt;number&gt;((a, b) =&gt; b - a);<br>  [3, 1, 4, 1, 5, 9, 2, 6].forEach(n =&gt; pq.enqueue(n));<br><br>  expect(pq.dequeue()).toBe(9);<br>  expect(pq.dequeue()).toBe(6);<br>  expect(pq.dequeue()).toBe(5);<br>});</pre><h3>Test 3 — peek() Doesn’t Remove</h3><pre>it(&#39;peek returns the top element without removing it&#39;, () =&gt; {<br>  const pq = new PriorityQueue&lt;number&gt;((a, b) =&gt; a - b);<br>  pq.enqueue(3);<br>  pq.enqueue(1);<br>  pq.enqueue(2);<br><br>  expect(pq.peek()).toBe(1);<br>  expect(pq.size).toBe(3); // still 3 — nothing was removed<br>  expect(pq.peek()).toBe(1); // still 1<br>});</pre><h3>Test 4 — Edge Cases</h3><p>Always test the empty state and single-element state — these are where off-by-one bugs hide:</p><pre>it(&#39;returns undefined when dequeuing an empty queue&#39;, () =&gt; {<br>  const pq = new PriorityQueue&lt;number&gt;((a, b) =&gt; a - b);<br>  expect(pq.dequeue()).toBeUndefined();<br>  expect(pq.peek()).toBeUndefined();<br>});<br><br>it(&#39;handles a single element correctly&#39;, () =&gt; {<br>  const pq = new PriorityQueue&lt;number&gt;((a, b) =&gt; a - b);<br>  pq.enqueue(42);<br><br>  expect(pq.peek()).toBe(42);<br>  expect(pq.size).toBe(1);<br>  expect(pq.dequeue()).toBe(42);<br>  expect(pq.isEmpty()).toBe(true);<br>});</pre><h3>Test 5 — Objects With Custom Comparator</h3><p>This proves the generic type system actually works end-to-end:</p><pre>interface Task {<br>  name: string;<br>  urgency: number;<br>}<br><br>it(&#39;handles objects with custom priority&#39;, () =&gt; {<br>  const pq = new PriorityQueue&lt;Task&gt;((a, b) =&gt; b.urgency - a.urgency);<br><br>  pq.enqueue({ name: &#39;Low&#39;,    urgency: 1 });<br>  pq.enqueue({ name: &#39;High&#39;,   urgency: 10 });<br>  pq.enqueue({ name: &#39;Medium&#39;, urgency: 5 });<br><br>  expect(pq.dequeue()?.name).toBe(&#39;High&#39;);<br>  expect(pq.dequeue()?.name).toBe(&#39;Medium&#39;);<br>  expect(pq.dequeue()?.name).toBe(&#39;Low&#39;);<br>});</pre><h3>Test 6 — fromArray (Heapify)</h3><pre>it(&#39;fromArray builds a valid heap&#39;, () =&gt; {<br>  const pq = PriorityQueue.fromArray([5, 3, 8, 1, 4], (a, b) =&gt; a - b);<br><br>  expect(pq.size).toBe(5);<br>  expect(pq.dequeue()).toBe(1);<br>  expect(pq.dequeue()).toBe(3);<br>  expect(pq.dequeue()).toBe(4);<br>});<br><br>it(&#39;fromArray does not mutate the original array&#39;, () =&gt; {<br>  const original = [3, 1, 2];<br>  PriorityQueue.fromArray(original, (a, b) =&gt; a - b);<br>  expect(original).toEqual([3, 1, 2]); // unchanged<br>});</pre><h3>Test 7 — Stress Test (Optional But Satisfying)</h3><p>This test inserts a large number of random values and verifies the output is always sorted. If the heap logic has any bug, this will almost certainly catch it:</p><pre>it(&#39;correctly orders 1000 random elements&#39;, () =&gt; {<br>  const pq = new PriorityQueue&lt;number&gt;((a, b) =&gt; a - b);<br>  const input = Array.from({ length: 1000 }, () =&gt; Math.floor(Math.random() * 10000));<br><br>  input.forEach(n =&gt; pq.enqueue(n));<br><br>  const output: number[] = [];<br>  while (!pq.isEmpty()) {<br>    output.push(pq.dequeue()!);<br>  }<br><br>  // Each element should be &gt;= the one before it<br>  for (let i = 1; i &lt; output.length; i++) {<br>    expect(output[i]).toBeGreaterThanOrEqual(output[i - 1]);<br>  }<br>});;</pre><h3>Running the Tests</h3><pre>npm test</pre><p>If everything is green, you have a battle-tested priority queue ready for production.</p><p><em>That’s the full series. If you found it useful, the code lives on GitHub at </em><a href="https://github.com/mojtaba-sabouri/priority-queue-ts">priority-queue-ts</a><em>. Feel free to open an issue or PR.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2b7ae866bfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heaps Explained: The Math Behind Priority Queues]]></title>
            <link>https://medium.com/@sabouri.dev/heaps-explained-the-math-behind-priority-queues-d43c6746f0d6?source=rss-d5474aae2d3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d43c6746f0d6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[priority-queue]]></category>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Mojtaba Sabouri]]></dc:creator>
            <pubDate>Mon, 11 May 2026 19:01:04 GMT</pubDate>
            <atom:updated>2026-05-18T20:39:15.865Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UTd85bz17JVnnagkV4O7Yw.png" /></figure><p><em>Part 2 of 3 — </em>Understanding Priority Queues in TypeScript</p><p>In Part 1, we talked about <em>what</em> a priority queue is and <em>why</em> you’d need one. Now comes the fun part — understanding <em>how</em> it actually works under the hood.</p><p>As we touched on in Part 1, there are a few ways to implement a priority queue — an unsorted array, a sorted array, or a heap. Each makes a different trade-off between how fast you can add elements and how fast you can remove them. But for the general case, one approach consistently wins: the <strong>heap</strong>.</p><p>I’ll be honest — when I first heard the word “heap”, I pictured a messy pile of things. Totally unordered. Chaotic.</p><p>It’s actually the opposite. A heap is one of the most elegant, mathematically clean structures I’ve come across. And by the end of this article, you’ll not only understand how it works — you’ll be able to <em>prove</em> why it works.</p><p>Let’s get into it.</p><h3>Why Not Just Use a Sorted Array?</h3><p>Before we talk about heaps, let’s ask the obvious question: why not just keep our priority queue as a sorted array?</p><p>You add an item → insert it in the right position to keep everything sorted → done.</p><p>It works. But let’s think about the cost.</p><p>Every time you add a new element, you need to find where it belongs and shift everything after it to make room. In the worst case, that’s touching every single element already in the array. With 1,000 elements, that could mean 1,000 shifts per insertion.</p><p>In computer science terms, that’s <strong>O(n)</strong> per insertion.</p><p>For small datasets, fine. But if you’re running Dijkstra’s algorithm on a graph with millions of nodes? Or processing a job queue with thousands of tasks per second? Suddenly O(n) per operation is catastrophic.</p><p>We need something better. We need <strong>O(log n)</strong>.</p><p>That’s what a heap gives us.</p><h3>What Is a Heap?</h3><p>A heap is a <strong>binary tree</strong> with two strict rules:</p><p><strong>Rule 1 — Shape Property:</strong> The tree must be <em>complete</em>. Every level is fully filled from left to right, with no gaps. You never start filling a new level until the previous one is finished.</p><p><strong>Rule 2 — Heap Property:</strong> Every parent must have a higher (or equal) priority than its children. Always. No exceptions.</p><p>That second rule is what makes a heap so useful for priority queues — the element with the highest priority is <em>always</em> sitting at the top, at the root of the tree. You never have to search for it.</p><h3>Min-Heap vs Max-Heap</h3><p>There are two flavours of heap, and the difference is simple:</p><p><strong>Min-Heap:</strong> The <em>smallest</em> value is at the top. Every parent is smaller than or equal to its children.</p><pre>        1<br>      /   \<br>     3     2<br>    / \   / \<br>   7   4 5   6</pre><p>Dequeue always gives you the smallest element first.</p><p><strong>Max-Heap:</strong> The <em>largest</em> value is at the top. Every parent is larger than or equal to its children.</p><pre>        9<br>      /   \<br>     7     8<br>    / \   / \<br>   3   4 5   6</pre><p>Dequeue always gives you the largest element first.</p><p>Which one you use depends entirely on what “highest priority” means in your problem. Lower number = more urgent? Use a min-heap. Higher score = more important? Use a max-heap.</p><p>In our TypeScript implementation (coming in Part 3), we’ll handle this with a <strong>comparator function</strong>, so you don’t have to choose upfront — the caller decides.</p><h3>The Clever Part: Storing a Tree in an Array</h3><p>Here’s where it gets really interesting.</p><p>At this point you might be thinking: OK, so I need to build a tree data structure, with nodes and pointers and left/right children…</p><p>Nope.</p><p>Because our heap is a <em>complete</em> binary tree (no gaps, always filled left to right), we can store the entire thing in a <strong>plain flat array</strong>. No node objects. No pointers. Just indices.</p><p>Take this min-heap tree:</p><pre>        1         (index 0)<br>      /   \<br>     3     2      (index 1, 2)<br>    / \   /<br>   7   4 5        (index 3, 4, 5)</pre><p>Stored as an array, it looks like this:</p><pre>Index:  0   1   2   3   4   5<br>Value: [1,  3,  2,  7,  4,  5]</pre><p>We just read the tree level by level, left to right, and write it into the array. The tree structure is completely preserved — we just need a formula to navigate it.</p><h3>The Index Formulas — And Why They Work</h3><p>This is the part most articles skip. They just hand you the formulas:</p><ul><li><strong>Left child</strong> of node at index p → 2p + 1</li><li><strong>Right child</strong> of node at index p → 2p + 2</li><li><strong>Parent</strong> of node at index c → Math.floor((c - 1) / 2)</li></ul><p>But <em>where do these come from?</em> Let me show you the actual derivation, step by step.</p><h3>Step 1: Start with a Simpler System (1-based indexing)</h3><p>Imagine for a moment that we number our array positions starting at <strong>1</strong> instead of 0. This is more intuitive for trees because the root becomes position 1.</p><p>In a 1-based system, the pattern is immediately obvious:</p><pre>p = 1  →  left: 2,  right: 3<br>p = 2  →  left: 4,  right: 5<br>p = 3  →  left: 6,  right: 7<br>p = 4  →  left: 8,  right: 9</pre><p>See it? The left child is always 2p, and the right child is always 2p + 1 (right child comes after left child, so it is located in +1 after the left).</p><p>Why? Because each level of the tree has <em>double</em> the nodes of the level above it. When you move from a parent to its children, you’re essentially doubling your position in line.</p><p>This gives us our base formulas (1-based):</p><pre>left child  = 2 * p<br><br>right child = 2 * p + 1  <br></pre><h3>Step 2: Convert to 0-based Indexing (What Arrays Actually Use)</h3><p>Now, programming arrays start at index <strong>0</strong>, not 1. So every position in our real array is exactly 1 less than in the 1-based system.</p><p>Let’s define two variables to keep things clear:</p><ul><li>p₀ = index in our 0-based array (what we actually use)</li><li>p₁ = position in the 1-based system</li></ul><p>The relationship between them: p₁ = p₀ + 1</p><p>Same for a child’s index c₀ and its 1-based position c₁: c₁ = c₀ + 1</p><p>Now we just do algebra.</p><p><strong>Deriving the Left Child Formula:</strong></p><p>Start with the 1-based formula:</p><pre>c₁ = 2 × p₁</pre><p>Substitute in our definitions (c₁ = c₀ + 1 and p₁ = p₀ + 1):</p><pre>c₀ + 1 = 2 × (p₀ + 1)<br>c₀ + 1 = 2p₀ + 2<br>c₀     = 2p₀ + 1</pre><p>✅ <strong>Left child of p is at index </strong><strong>2p + 1</strong></p><p><strong>Deriving the Right Child Formula:</strong></p><p>Start with the 1-based formula:</p><pre>c₁ = 2 × p₁ + 1</pre><p>Substitute:</p><pre>c₀ + 1 = 2 × (p₀ + 1) + 1<br>c₀ + 1 = 2p₀ + 2 + 1<br>c₀ + 1 = 2p₀ + 3<br>c₀     = 2p₀ + 2</pre><p>✅ <strong>Right child of p is at index </strong><strong>2p + 2</strong></p><p><strong>Deriving the Parent Formula:</strong></p><p>The parent formula is just the reverse of the child formulas. Let c be any child&#39;s index.</p><p>If it’s a left child: c = 2p + 1, so p = (c - 1) / 2</p><p>If it’s a right child: c = 2p + 2, so p = (c - 2) / 2 = (c - 1) / 2 - 0.5</p><p>Notice that in both cases, Math.floor((c - 1) / 2) gives the correct parent index:</p><ul><li>For a left child, the result is exact.</li><li>For a right child, the floor discards the trailing .5.</li></ul><p>✅ <strong>Parent of c is at index </strong><strong>Math.floor((c - 1) / 2)</strong></p><h3>Let’s Verify With a Real Example</h3><p>Going back to our array [1, 3, 2, 7, 4, 5]:</p><p>Node at index 1 (value 3):</p><ul><li>Left child: 2(1) + 1 = 3 → value 7 ✅</li><li>Right child: 2(1) + 2 = 4 → value 4 ✅</li><li>Parent: floor((1-1)/2) = 0 → value 1 ✅</li></ul><p>Node at index 4 (value 4):</p><ul><li>Parent: floor((4-1)/2) = floor(1.5) = 1 → value 3 ✅</li></ul><p>Every relationship in the tree, navigated purely with arithmetic on indices. No pointers needed.</p><h3>How the Heap Stays Ordered: Sift Up &amp; Sift Down</h3><p>Now that we understand the structure, we need to understand the two operations that keep it valid.</p><h3>Sift Up (used after adding an element)</h3><p>When you add a new element, you place it at the <strong>end</strong> of the array — which in tree terms means the next available slot, filling left to right on the bottom level. But it might have a higher priority than its parent — which would violate the heap property.</p><p>So you <strong>sift it up</strong>:</p><ol><li>Compare the new element with its parent.</li><li>If the new element has higher priority, swap them.</li><li>Repeat from the new position, until the element reaches a spot where its parent has higher (or equal) priority — or until it reaches the root.</li></ol><p>Each swap moves one level up. “Since a complete binary tree of n elements has a height of log₂(n) levels — each level doubles the number of nodes, so the height grows very slowly relative to n — this operation is at most <strong>O(log n).</strong>”</p><p><strong>Example — adding </strong><strong>2 to this min-heap:</strong></p><pre>Step 1 — enqueue: place 2 at the next left-to-right slot (left child of 7)<br><br>      5<br>    /   \<br>   7     8<br>  /<br> 2<br><br>Array: [5, 7, 8, 2]<br><br>Step 2 — 2 has higher priority than its parent 7 → swap<br><br>      5<br>    /   \<br>   2     8<br>  /<br> 7<br><br>Array: [5, 2, 8, 7]<br><br>Step 3 — 2 has higher priority than its parent 5 → swap<br><br>      2<br>    /   \<br>   5     8<br>  /<br> 7<br><br>Array: [2, 5, 8, 7] ✅</pre><h3>Sift Down (used after removing an element)</h3><p>When you remove the top element (the highest priority), you can’t just leave a hole at the root. Instead:</p><ol><li>Take the <strong>last element</strong> in the array and move it to the root.</li><li>This element probably doesn’t belong at the top — so <strong>sift it down</strong>.</li><li>Compare it with its children. If a child has higher priority, swap with the <em>higher-priority child</em>.</li><li>Repeat until the element is in a valid position.</li></ol><p>Again, at most <strong>O(log n)</strong> swaps.</p><h3>Why This Is So Efficient</h3><p>Let’s compare the three implementation approaches side by side:</p><pre>Unsorted Array → Enqueue: O(1)    Dequeue: O(n)     Peek: O(n)<br>Sorted Array   → Enqueue: O(n)    Dequeue: O(1)     Peek: O(1)<br>Heap           → Enqueue: O(logn) Dequeue: O(log n) Peek: O(1) ✅</pre><p>The heap wins because it doesn’t do more work than it has to. It doesn’t keep everything perfectly sorted — it just keeps enough order so that the <em>top element is always correct</em>. That laziness is actually its strength.</p><h3>Quick Recap</h3><ul><li>A <strong>heap</strong> is a complete binary tree where every parent has higher priority than its children</li><li>The <strong>min-heap</strong> puts the smallest value at the top; the <strong>max-heap</strong> puts the largest</li><li>Heaps are stored in <strong>flat arrays</strong> — no tree nodes or pointers needed</li><li>The index formulas (2p+1, 2p+2, floor((c-1)/2)) come directly from converting the natural &quot;doubling&quot; pattern of binary trees from 1-based to 0-based indexing</li><li><strong>Sift Up</strong> and <strong>Sift Down</strong> maintain the heap property in O(log n)</li></ul><h3>What’s Next?</h3><p>In <strong>Part 3</strong>, we put all of this into practice.</p><p>We’ll write a complete, generic PriorityQueue&lt;T&gt; class in TypeScript from scratch — with a custom comparator, full sift up/down logic, a fromArray heapify method, and proper TypeScript best practices throughout.</p><p>Every single line of code will be explained. No skipping, no hand-waving.</p><p>See you in Part 3.<br><em>(Link coming soon.)</em></p><p><em>This is Part 2 of a 3-part series on Priority Queues.</em></p><p><a href="https://medium.com/@sabouri.dev/what-is-a-queue-and-why-does-priority-matter-69936d3c7b9c"><em>← Part 1: What is a Queue, and Why Does Priority Matter?</em></a></p><p><em>→ Part 3: </em><a href="https://medium.com/@sabouri.dev/building-a-priority-queue-from-scratch-in-typescript-f2b7ae866bfa"><em>Building a Priority Queue from Scratch in TypeScript</em></a></p><p>If you enjoyed this article, follow for the next parts of the series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d43c6746f0d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is a Queue, and Why Does Priority Matter?]]></title>
            <link>https://medium.com/@sabouri.dev/what-is-a-queue-and-why-does-priority-matter-69936d3c7b9c?source=rss-d5474aae2d3a------2</link>
            <guid isPermaLink="false">https://medium.com/p/69936d3c7b9c</guid>
            <category><![CDATA[queue]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[priority-queue]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Mojtaba Sabouri]]></dc:creator>
            <pubDate>Sun, 10 May 2026 21:21:54 GMT</pubDate>
            <atom:updated>2026-05-19T19:59:40.352Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMyBySSD7FjLUoTbWCzPxg.png" /></figure><h3>Part 1 of 3 — Understanding Priority Queues in TypeScript</h3><p>I’ve been working on a TypeScript package recently, and at some point, I needed to process tasks not just in arrival order, but based on urgency.</p><p>That’s when I fell into the rabbit hole of priority queues.</p><p>The deeper I went, the more I realised priority queues are everywhere once you know how to spot them.</p><p>In this series, I’m going to walk through everything — from what a basic queue is, all the way to building a fully working, generic priority queue in TypeScript from scratch.</p><p>No hand-waving. No skipping the hard parts.</p><p>Let’s start at the beginning.</p><h3>First — What Even Is a Queue?</h3><p>A queue is one of the most natural data structures in computer science because it mirrors how lines work in real life.</p><p>Think of it like a queue at a coffee shop. The first person who walks in gets served first. The second person waits. The third person waits even longer. Nobody cuts in line. At least in theory.</p><p>This principle is called <strong>FIFO</strong> — <em>First In, First Out</em>.</p><p>In code, a basic queue gives you two operations:</p><ul><li><strong>Enqueue</strong> — add something to the back of the line</li><li><strong>Dequeue</strong> — remove and return the item at the front</li></ul><p>That’s it. Simple, predictable, and fair.</p><pre>Enqueue: [A] → [A, B] → [A, B, C]<br>Dequeue:        [B, C] → [C]<br>(A came first, so A leaves first)</pre><p>A very simple queue implementation in TypeScript might look like this:</p><pre>class Queue&lt;T&gt; {<br>  private items: T[] = [];<br><br>  enqueue(item: T) {<br>    this.items.push(item);<br>  }<br><br>  dequeue() {<br>    return this.items.shift();<br>  }<br>}</pre><p>This works perfectly for FIFO behaviour.</p><p>But it also reveals the limitation of normal queues:</p><p>Everything is treated equally.</p><p>Queues are used everywhere:</p><ul><li>Handling HTTP requests on a server</li><li>Managing print jobs</li><li>Processing messages in event-driven systems</li><li>Scheduling background work</li></ul><p>Whenever order matters, and you want fairness, a queue is usually the right tool.</p><h3>So What’s the Problem?</h3><p>Here’s where things get interesting.</p><p>Fairness is great — until it isn’t.</p><p>Imagine a hospital emergency room. If patients were treated using a strict FIFO order, the person who arrived first would always be seen first.</p><p>That sounds fair on paper. But what if patient #1 has a mild headache, while patient #4 just arrived with chest pain?</p><p>Strict FIFO would force the critical patient to wait. That’s not just inefficient — it’s dangerous. Or think about your operating system.</p><p>Right now, while you’re reading this, your OS is juggling dozens (maybe hundreds) of processes. Should every process receive equal attention?</p><p>Of course not.</p><p>A keyboard input needs to be handled almost instantly, while a background file sync can wait a few seconds.</p><p>This is the core problem a normal queue can’t solve:</p><blockquote><em>Not everything deserves to wait its turn.</em></blockquote><h3>Introducing the Priority Queue</h3><p>A priority queue is like a queue that’s been given a brain.</p><p>Instead of asking:</p><blockquote><em>“Who got here first?”</em></blockquote><p>It asks:</p><blockquote><em>“Who needs to go next?”</em></blockquote><p>Each element added to a priority queue comes with a priority value.</p><p>When you dequeue, you don’t get the oldest item — you get the item with the highest priority, regardless of when it arrived.</p><pre>Add: Task A (priority 2)<br>Add: Task B (priority 1) ← highest priority<br>Add: Task C (priority 3)</pre><pre>Dequeue order: B → A → C</pre><p>Task B goes first even though it wasn’t added first.</p><p>That’s the key difference.</p><p>In many implementations, if two elements share the same priority, they are processed in FIFO order among themselves — the one added first comes out first.</p><h3>Where Are Priority Queues Actually Used?</h3><p>Priority queues are not just academic concepts. They appear in some of the most important algorithms and systems in software engineering.</p><h3>Dijkstra’s Shortest Path Algorithm</h3><p>When your GPS calculates the fastest route, it’s exploring possible paths. At each step, it needs to process the <em>closest unvisited node</em> first. A priority queue makes that fast and efficient. If you already know BFS, think of Dijkstra’s as BFS with a priority queue instead of a regular queue — that one change is what makes it work on weighted graphs.</p><h3>A* Search Algorithm</h3><p>Used heavily in game development and robotics for pathfinding.</p><p>The algorithm always explores the most promising path next. Without a priority queue, this becomes dramatically slower.</p><h3>Operating System Schedulers</h3><p>Your operating system constantly decides which process gets CPU time next. High-priority tasks — like user input — are processed before lower-priority background tasks.</p><h3>Event-Driven Simulations</h3><p>In simulations such as traffic systems or network models, events are processed based on when they should happen, not when they were inserted into the system.</p><p>The next event to process is always the earliest scheduled one.</p><h3>Backend Task Queues</h3><p>If you’ve ever built a job queue for sending emails, resizing images, or delivering notifications, you already know that some jobs matter more than others.</p><p>A priority queue allows urgent jobs to jump ahead.</p><h3>What Makes a Good Priority Queue?</h3><p>Before getting into implementation details, it’s worth thinking about what we actually need from a priority queue.</p><p>At minimum, we want to:</p><ul><li>Add an element with a priority</li><li>Remove the highest-priority element quickly</li><li>Peek at the highest-priority element without removing it</li></ul><p>The important word here is:</p><p><strong>Quickly.</strong></p><p>Priority queues are often used in systems processing thousands — sometimes millions — of items. The efficiency of each operation matters a lot. In the next article, we’ll look at the data structure that makes this possible efficiently: the binary heap.</p><h3>Quick Recap</h3><ul><li><strong>Queue</strong> — FIFO, first in, first out. Simple and fair.</li><li><strong>Priority Queue</strong> — highest priority out first, regardless of arrival order.</li><li><strong>Use cases</strong> — pathfinding, OS scheduling, task queues, simulations.</li><li><strong>Key operations</strong> — Enqueue, Dequeue, Peek.</li></ul><h3>What’s Next?</h3><p>In <a href="https://medium.com/@sabouri.dev/heaps-explained-the-math-behind-priority-queues-d43c6746f0d6">Part 2</a>, we’ll dig into the data structure powering most priority queue implementations: the binary heap.</p><p>We’ll cover:</p><ul><li>What min-heaps and max-heaps are</li><li>Why are heaps stored in arrays instead of actual tree objects?</li><li>The mathematical reasoning behind heap index formulas — explained clearly enough that you could teach it to someone else</li></ul><p>See you in <a href="https://medium.com/@sabouri.dev/heaps-explained-the-math-behind-priority-queues-d43c6746f0d6">Part 2</a>.</p><p>This is Part 1 of a 3-part series on Priority Queues.</p><p>→ <a href="https://medium.com/@sabouri.dev/heaps-explained-the-math-behind-priority-queues-d43c6746f0d6">Part 2: <em>Heaps Explained — The Math Behind Priority Queues</em></a></p><p>→ <a href="https://medium.com/@sabouri.dev/building-a-priority-queue-from-scratch-in-typescript-f2b7ae866bfa">Part 3: <em>Building a Priority Queue from Scratch in TypeScript</em></a></p><p>If you enjoyed this article, follow for the next parts of the series.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69936d3c7b9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>