-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
86 lines (71 loc) · 2.71 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
77
78
79
80
81
82
83
84
85
86
const axios = require('axios').default;
const APP_ID = "tfl_key"
const APP_KEY = "c918382153274eef95ca07f91a280c17"
const readlineSync = require("readline-sync");
class Bus {
constructor(route, destination, timeToArrival) {
this.route = route
this.destination = destination
this.timeToArrival = timeToArrival
}
listBus = () => {
console.log(`- The ${this.route} to ${this.destination} will arrive in ${this.timeToArrival} mins.`)
}
}
const sortBusesByTime = (busData) => {
return busData.sort((a, b) => {
return a.timeToStation - b.timeToStation
})
}
// NW5 1TL
const postCode = readlineSync.question('Please enter your post code: ')
const getPostCodeData = (postCode) => {
axios.get(`https://api.postcodes.io/postcodes/${postCode}`)
.then((response) => {
getBusStopCodes([response.data.result.latitude, response.data.result.longitude])
})
.catch((error) => {
console.log(error)
})
}
getPostCodeData(postCode)
const sortStopsByDistance = (stops) => {
return stops.sort((a, b) => {
return a.distance - b.distance
})
}
const getBusStopCodes = (latAndLon) => {
const [lat, lon] = latAndLon
axios.get(`https://api.tfl.gov.uk/Stoppoint?lat=${lat}&lon=${lon}&stoptypes=NaptanBusCoachStation,NaptanPublicBusCoachTram&radius=500`)
.then((response) => {
const stopPoints = response.data.stopPoints
const sortedStops = sortStopsByDistance(stopPoints)
const nearestStops = sortedStops.slice(0, 2)
nearestStops.forEach(async (stop) => {
getNextFiveBuses(stop.naptanId)
.then((buses) => {
console.log(`${stop.commonName} is a distance of ${stop.distance.toFixed(2)}m away. The next buses are:`)
buses.forEach((bus) => bus.listBus())
})
})
})
.catch((error) => {
console.log(error)
})
}
const getNextFiveBuses = (busStopCodes) => {
return axios.get(`https://api.tfl.gov.uk/StopPoint/${busStopCodes}/Arrivals?app_id=${APP_ID}&app_key=${APP_KEY}`)
.then((response) => {
const sortedData = sortBusesByTime(response.data)
const nextFiveBuses = sortedData.slice(0, 5)
const buses = []
nextFiveBuses.forEach((busData) => {
const bus = new Bus(busData.lineName, busData.destinationName, busData.timeToStation)
buses.push(bus)
})
return buses
})
.catch((error) => {
console.log(error)
})
}