Skip to content

Instantly share code, notes, and snippets.

@samkcarlile
Last active July 6, 2023 17:12
Show Gist options
  • Save samkcarlile/711f1825fd3f13f6a7ba25c2d1aee91d to your computer and use it in GitHub Desktop.
Save samkcarlile/711f1825fd3f13f6a7ba25c2d1aee91d to your computer and use it in GitHub Desktop.
// tree node type
type Node = {
  id: number;
  children: () => Promise<Node[]>
}

// results array
const results: Node[] = [];

Imagine a tree data structure where the children are retrieved asynchronously. The goal is to traverse this tree depth-first while achieving maximum parallelization. It is straightforward to write an implementation that simply awaits the children() when it's encountered:

async function traverseDepthFirst(root: Node): Promise<number[]> {
  const results: number[] = [];
  
  const stack: Node[] = [root];
  while (stack.length) {
    const { data, children } = stack.pop();
    results.push(data);
    
    for (const child of await children()) {
      stack.push(child);
    }
  }
  
  return results;
}

To parallelize this, it's possible to execute multiple node.children() async calls at the same time as long as they are on the same level in the tree. The difficulty with parallelizing the traversal is that these Promises may complete at any time, but we want the results array to respect DFS order. Imgur

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment