Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions src/algorithms/shortestPath/getPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import type { TraversingTracks } from './types.js';

import { Graph } from '../../Graph.js';

export function addWeightFunction(edgeWeight: number, currentPathWeight: number | undefined, hop: number): number {
if (currentPathWeight === undefined) {
return edgeWeight;
}
return edgeWeight + currentPathWeight;
}

/**
* Assembles the shortest path by traversing the
* predecessor subgraph from destination to source.
Expand All @@ -12,22 +19,25 @@ export function getPath<Node, LinkProps>(
tracks: TraversingTracks<NoInfer<Node>>,
source: NoInfer<Node>,
destination: NoInfer<Node>,
weightFunction: (edgeWeight: number, currentPathWeight: number, hop: number) => number = addWeightFunction
): {
nodes: [Node, Node, ...Node[]];
weight: number;
} {
const { p } = tracks;
const nodeList: Node[] & { weight?: EdgeWeight } = [];

let totalWeight = 0;
let totalWeight = undefined as unknown as EdgeWeight;
let node = destination;

let hop = 1;
while (p.has(node)) {
const currentNode = p.get(node)!;

nodeList.push(node);
totalWeight += graph.getEdgeWeight(currentNode, node);
totalWeight = weightFunction(graph.getEdgeWeight(currentNode, node), totalWeight, hop);
node = currentNode;
hop++;
}

if (node !== source) {
Expand Down
5 changes: 3 additions & 2 deletions src/algorithms/shortestPath/shortestPath.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Graph } from '../../Graph.js';
import { NoInfer } from '../../types.js';
import { dijkstra } from './dijkstra.js';
import { getPath } from './getPath.js';
import { getPath, addWeightFunction } from './getPath.js';
import { TraversingTracks } from './types.js';

/**
Expand All @@ -13,6 +13,7 @@ export function shortestPath<Node, LinkProps>(
graph: Graph<Node, LinkProps>,
source: NoInfer<Node>,
destination: NoInfer<Node>,
weightFunction: (edgeWeight: number, currentPathWeight: number, hop: number) => number = addWeightFunction
): {
nodes: [Node, Node, ...Node[]];
weight: number;
Expand All @@ -25,5 +26,5 @@ export function shortestPath<Node, LinkProps>(

dijkstra(graph, tracks, source, destination);

return getPath(graph, tracks, source, destination);
return getPath(graph, tracks, source, destination, weightFunction);
}