-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathAStar.test.js
More file actions
67 lines (59 loc) · 1.4 KB
/
Copy pathAStar.test.js
File metadata and controls
67 lines (59 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { aStarSearch } from '../AStar.js'
const graph = {
A: [
['B', 1],
['C', 4]
],
B: [
['C', 1],
['D', 5]
],
C: [['D', 1]],
D: []
}
const heuristics = { A: 2, B: 2, C: 1, D: 0 }
const heuristic = (node) => heuristics[node]
const zeroHeuristic = () => 0
test('Finds the shortest path using an admissible heuristic', () => {
expect(aStarSearch(graph, 'A', 'D', heuristic)).toEqual({
path: ['A', 'B', 'C', 'D'],
cost: 3
})
})
test('Matches Dijkstra (zero heuristic) on the same graph', () => {
expect(aStarSearch(graph, 'A', 'D', zeroHeuristic)).toEqual({
path: ['A', 'B', 'C', 'D'],
cost: 3
})
})
test('Returns a path with cost 0 when start equals target', () => {
expect(aStarSearch(graph, 'A', 'A', heuristic)).toEqual({
path: ['A'],
cost: 0
})
})
test('Returns null when no path exists', () => {
const disconnectedGraph = { A: [['B', 1]], B: [], C: [] }
expect(aStarSearch(disconnectedGraph, 'A', 'C', zeroHeuristic)).toBeNull()
})
test('Finds the shortest path in a larger graph with multiple routes', () => {
const largerGraph = {
A: [
['B', 2],
['C', 5]
],
B: [
['D', 4],
['E', 2]
],
C: [['E', 1]],
D: [['F', 1]],
E: [['F', 4]],
F: []
}
const largerHeuristic = () => 0
expect(aStarSearch(largerGraph, 'A', 'F', largerHeuristic)).toEqual({
path: ['A', 'B', 'D', 'F'],
cost: 7
})
})