dijkstra.test.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. 'use strict';
  2. var expect = require('expect.js');
  3. var dijkstra = require('../dijkstra.js');
  4. var find_path = dijkstra.find_path;
  5. describe('dijkstra.js', function () {
  6. describe('.find_path()', function () {
  7. it('should find the path between two points, all edges have weight 1', function () {
  8. // A B C
  9. // D E F
  10. // G H I
  11. var graph = {
  12. a: {b: 10, d: 1},
  13. b: {a: 1, c: 1, e: 1},
  14. c: {b: 1, f: 1},
  15. d: {a: 1, e: 1, g: 1},
  16. e: {b: 1, d: 1, f: 1, h: 1},
  17. f: {c: 1, e: 1, i: 1},
  18. g: {d: 1, h: 1},
  19. h: {e: 1, g: 1, i: 1},
  20. i: {f: 1, h: 1}
  21. };
  22. var path = find_path(graph, 'a', 'i');
  23. expect(path).to.eql(['a', 'd', 'e', 'f', 'i']);
  24. });
  25. it('should find the path between two points, weighted edges', function () {
  26. var graph = {
  27. a: {b: 10, c: 100, d: 1},
  28. b: {c: 10},
  29. d: {b: 1, e: 1},
  30. e: {f: 1},
  31. f: {c: 1},
  32. g: {b: 1}
  33. };
  34. var path = find_path(graph, 'a', 'c');
  35. expect(path).to.eql(['a', 'd', 'e', 'f', 'c']);
  36. path = find_path(graph, 'd', 'b');
  37. expect(path).to.eql(['d', 'b']);
  38. });
  39. it('should throw on unreachable destination', function () {
  40. var graph = {
  41. a: {b: 10, c: 100, d: 1},
  42. b: {c: 10},
  43. d: {b: 1, e: 1},
  44. e: {f: 1},
  45. f: {c: 1},
  46. g: {b: 1}
  47. };
  48. expect(function () { find_path(graph, 'c', 'a'); }).to.throwException();
  49. expect(function () { find_path(graph, 'a', 'g'); }).to.throwException();
  50. });
  51. it('should throw on non-existent destination', function () {
  52. var graph = {
  53. a: {b: 10, c: 100, d: 1},
  54. b: {c: 10},
  55. d: {b: 1, e: 1},
  56. e: {f: 1},
  57. f: {c: 1},
  58. g: {b: 1}
  59. };
  60. expect(function () { find_path(graph, 'a', 'z'); }).to.throwException();
  61. });
  62. });
  63. describe('.single_source_shortest_paths()', function () {
  64. it('should find all paths from a node', function () {
  65. var graph = {
  66. a: {b: 10, c: 100, d: 1},
  67. b: {c: 10},
  68. d: {b: 1, e: 1},
  69. e: {f: 1},
  70. f: {c: 1},
  71. g: {b: 1}
  72. };
  73. // All paths from 'a'
  74. var paths = dijkstra.single_source_shortest_paths(graph, 'a');
  75. expect(paths).to.eql({
  76. d: 'a',
  77. b: 'd',
  78. e: 'd',
  79. f: 'e',
  80. c: 'f'
  81. });
  82. });
  83. });
  84. });