diff --git a/src/algorithms/shortestPath/getPath.ts b/src/algorithms/shortestPath/getPath.ts index 8ce82e9..4f2b9d5 100644 --- a/src/algorithms/shortestPath/getPath.ts +++ b/src/algorithms/shortestPath/getPath.ts @@ -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. @@ -12,6 +19,7 @@ export function getPath( tracks: TraversingTracks>, source: NoInfer, destination: NoInfer, + weightFunction: (edgeWeight: number, currentPathWeight: number, hop: number) => number = addWeightFunction ): { nodes: [Node, Node, ...Node[]]; weight: number; @@ -19,15 +27,17 @@ export function getPath( 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) { diff --git a/src/algorithms/shortestPath/shortestPath.ts b/src/algorithms/shortestPath/shortestPath.ts index 3289dab..3aa4d63 100644 --- a/src/algorithms/shortestPath/shortestPath.ts +++ b/src/algorithms/shortestPath/shortestPath.ts @@ -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'; /** @@ -13,6 +13,7 @@ export function shortestPath( graph: Graph, source: NoInfer, destination: NoInfer, + weightFunction: (edgeWeight: number, currentPathWeight: number, hop: number) => number = addWeightFunction ): { nodes: [Node, Node, ...Node[]]; weight: number; @@ -25,5 +26,5 @@ export function shortestPath( dijkstra(graph, tracks, source, destination); - return getPath(graph, tracks, source, destination); + return getPath(graph, tracks, source, destination, weightFunction); }