npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

batching-toposort

v1.2.0

Published

Efficiently sort interdependent tasks into a sequence of concurrently-executable batches.

Downloads

52,507

Readme

Batching-Toposort

npm version Build Status code style: prettier

Efficiently sort interdependent tasks into a sequence of concurrently-executable batches.

batchingToposort :: { DependencyId : [DependentId] } -> [[TaskId]]
  • O(t + d) time complexity (for t tasks and d dependency relationships)
  • O(t) space complexity
  • Zero package dependencies
  • Thoroughly tested (including invariant tests)
  • Errors on cyclic graphs

Motivation

Often one needs to schedule interdependent tasks. In order to determine task order, the classic solution is to use topological sort. However, toposort typically outputs a list of individual tasks, without grouping those that can be executed concurrently. Batching-Toposort takes this additional consideration into account, producing a list of lists of tasks. The outer list is ordered; each inner list is unordered.

Usage

npm install batching-toposort

Batching-Toposort expects a directed acyclic graph (DAG) implemented via adjacency list. In other words, construct an object whose keys are dependency IDs, and whose values are lists of dependent IDs.

const batchingToposort = require('batching-toposort')

// DAG :: { DependencyId : [DependentId] }
const DAG = {
    a: ['c', 'f'], // `a` is a dependency of `c` and `f`
    b: ['d', 'e'],
    c: ['f'],
    d: ['f', 'g'],
    e: ['h'],
    f: ['i'],
    g: ['j'],
    h: ['j'],
    i: [],
    j: [],
}

// batchingToposort :: DAG -> [[TaskId]]
const taskBatches = batchingToposort(DAG)
// [['a', 'b'], ['c', 'd', 'e'], ['f', 'g', 'h'], ['i', 'j']]

(If there is demand, Batching-Toposort may one day include a small DAG API and/or DOT support for convenience, but as of now it is the developer's role to construct the graph.)

Implementation

In short, Batching-Toposort adapts Kahn's Algorithm by inserting each round of root tasks into sublists rather than appending tasks directly to the main output list.

The classic DAG toposort keeps track of each task's in-degree (number of dependencies). As root tasks (those with no dependencies) are added to the output list, their dependents' in-degree counts are decremented. For a task to become a root, all of its dependencies must have been accounted for. The core algorithm is illustrated below in pseudocode (the actual implementation is in src/index.js).

given G = adjacency list of tasks and dependents (~O(1) lookup):

let N = map from tasks to in-degree counts (~O(1) lookup / update)
let L = [] (empty output list) (~O(1) append)
let R1 = list of root tasks (~O(1) addition, ~O(n) iteration)

while R1 is nonempty
    append R1 to L
    let R2 = [] (empty list for next batch) (~O(1) append)
    for each task T in R1
        for each dependent D of T (as per G)
            decrement in-degree count for D (in N)
            if D's in-degree (as per N) is 0
                add D to R2
    R1 = R2

return L

Performance

The time complexity is O(|V| + |E|) for V task vertices and E dependency edges.

  • The algorithm loops through rounds of roots, and every task is only a root only once, contributing to O(|V|) rounds (worst case is a linked list of tasks).
  • Each round handles a disjoint set of dependency edges (those rooted in that round's tasks), so the O(|E|) handling of all edges is effectively distributed across rounds.
  • Other operations, e.g. querying a node's in-degree (average case O(1)), are carefully managed to preserve the time complexity.

The space complexity is slightly better at O(|V|).

  • The in-degree map size is proportional to the number of vertices |V|, but not edges, as those are folded into an integer count during map construction.
  • The output by definition contains |V| tasks (distributed among as many or fewer lists).
  • Again, other operations are controlled to keep space complexity low.