-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
76 lines (54 loc) · 1.4 KB
/
index.js
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
68
69
70
71
72
73
74
75
76
var createPaths = require('create-paths');
module.exports = directions;
function directions() {
if( !( this instanceof directions ) ) {
return new directions();
}
this.stateCount = 1;
this.states = {};
this.idToState = {};
this.road = [];
this.traverse = null;
this.durations = {};
}
directions.prototype = {
fromTo: function( from, to, duration ) {
if( duration !== undefined ) {
var durations = this.durations[ from ] || ( this.durations[ from ] = {} );
durations[ to ] = duration;
this.road.push( [ from,
to,
duration ] );
this.traverse = createPaths(this.road);
} else {
duration = this.durations[ from ] && this.durations[ from ][ to ];
}
return duration;
},
getPath: function() {
var totalCost = 0;
var totalPath = [];
var from;
var to;
var info;
var cost;
var path;
for( var i = 1, len = arguments.length; i < len; i++ ) {
from = arguments[ i - 1 ];
to = arguments[ i ];
info = this.traverse(from, to);
cost = info.duration;
path = info.path;
// if we have multiple destinations and it's not the first remove the first
if(i > 1) {
path.shift();
}
totalCost += cost;
totalPath = totalPath.concat( path );
}
return {
cost: totalCost,
path: totalPath
};
}
};