Dijkstra's Algorithm Implementation

1.0.3 · maintenance · verified Sun Apr 19

dijkstrajs is a lightweight, zero-dependency JavaScript library that provides a straightforward implementation of Dijkstra's single-source shortest-paths algorithm. Currently at version 1.0.3, the package was last published over three years ago, indicating a mature and stable codebase rather than active feature development. It is designed for use in Node.js environments and offers a simple API for finding the shortest path between two nodes in a weighted graph. While other Dijkstra implementations might offer performance optimizations like priority queues, dijkstrajs prioritizes simplicity and ease of integration for basic graph traversal needs. Developers should note its inherent limitation of not supporting negative edge weights, which is a fundamental constraint of Dijkstra's algorithm itself.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a weighted graph using an adjacency list and then use `findPath` to calculate the shortest path between specified start and end nodes.

import { findPath } from 'dijkstrajs';

const graph = {
  A: { B: 1, C: 4 },
  B: { A: 1, C: 2, D: 5 },
  C: { A: 4, B: 2, D: 1 },
  D: { B: 5, C: 1 },
  E: { F: 3 }, // Disconnected node
  F: { E: 3 }
};

// Find the shortest path from node A to node D
const pathAD = findPath(graph, 'A', 'D');
console.log('Path from A to D:', pathAD); // Expected: [ 'A', 'B', 'C', 'D' ]

// Find the shortest path from node A to node E (unreachable)
const pathAE = findPath(graph, 'A', 'E');
console.log('Path from A to E:', pathAE); // Expected: null (or similar indication of no path)

// Example with different start/end
const pathBD = findPath(graph, 'B', 'D');
console.log('Path from B to D:', pathBD); // Expected: [ 'B', 'C', 'D' ]

view raw JSON →