@@ -3,6 +3,7 @@ import type { TraversingTracks } from './types.js';
33import type { NextWeightFnParams } from '../../types.js' ;
44
55import { Graph } from '../../Graph.js' ;
6+ import { invariant } from '../../invariant.js' ;
67
78/**
89 * Computes edge weight as the sum of all the edges in the path.
@@ -23,34 +24,22 @@ export function getPath<Node, LinkProps>(
2324 tracks : TraversingTracks < NoInfer < Node > > ,
2425 source : NoInfer < Node > ,
2526 destination : NoInfer < Node > ,
26- nextWeightFn : ( params : NextWeightFnParams ) => number = addWeightFunction ,
27+ nextWeightFn : (
28+ params : NextWeightFnParams < Node , LinkProps > ,
29+ ) => number = addWeightFunction ,
2730) : {
2831 nodes : [ Node , Node , ...Node [ ] ] ;
2932 weight : number | undefined ;
3033} {
3134 const { p } = tracks ;
32- const nodeList : Node [ ] & { weight ?: EdgeWeight } = [ ] ;
35+ const nodeList : Node [ ] = [ ] ;
3336
34- let totalWeight : EdgeWeight | undefined = undefined ;
3537 let node = destination ;
3638
37- let hop = 1 ;
3839 while ( p . has ( node ) ) {
3940 const currentNode = p . get ( node ) ! ;
40-
4141 nodeList . push ( node ) ;
42- const edgeWeight = graph . getEdgeWeight ( currentNode , node ) ;
43- totalWeight = nextWeightFn ( {
44- edgeWeight,
45- currentPathWeight : totalWeight ,
46- hop : hop ,
47- graph : graph ,
48- path : tracks ,
49- previousNode : node ,
50- currentNode : currentNode ,
51- } ) ;
5242 node = currentNode ;
53- hop ++ ;
5443 }
5544
5645 if ( node !== source ) {
@@ -60,6 +49,30 @@ export function getPath<Node, LinkProps>(
6049 nodeList . push ( node ) ;
6150 nodeList . reverse ( ) ;
6251
52+ invariant ( nodeList . length >= 2 , 'The path should have a least two nodes' ) ;
53+
54+ let totalWeight : EdgeWeight | undefined = undefined ;
55+
56+ // We start as index=1 to work on the first edge between node 0 and 1
57+ for ( let i = 1 ; i < nodeList . length ; i ++ ) {
58+ const previousNode = nodeList [ i - 1 ] ! ;
59+ const currentNode = nodeList [ i ] ! ;
60+
61+ const edgeWeight = graph . getEdgeWeight ( previousNode , currentNode ) ;
62+ const edgeProps = graph . getEdgeProperties ( previousNode , currentNode ) ! ;
63+
64+ totalWeight = nextWeightFn ( {
65+ edgeWeight,
66+ currentPathWeight : totalWeight ,
67+ hop : i ,
68+ graph,
69+ path : nodeList as [ Node , Node , ...Node [ ] ] ,
70+ previousNode,
71+ currentNode,
72+ props : edgeProps ,
73+ } ) ;
74+ }
75+
6376 return {
6477 nodes : nodeList as [ Node , Node , ...Node [ ] ] ,
6578 weight : totalWeight ,
0 commit comments