diff --git a/back/data/realtime.js b/back/data/realtime.js index 3e10a01..e24eef3 100644 --- a/back/data/realtime.js +++ b/back/data/realtime.js @@ -1,7 +1,22 @@ const tam = require('./sources/tam'); const util = require('../util'); +/** + * Comparison function between two stop passings. + * + * @param passing1 First stop passing. + * @param passing2 Second stop passing. + * @return Negative value if passing1 is sooner than passing2, positive + * otherwise, zero if they occur at the same time. + */ +const passingCompare = ({arrivalTime: time1}, {arrivalTime: time2}) => ( + time1 - time2 +); + +// Time at which the course data needs to be updated next let nextUpdate = null; + +// Current information about courses let currentCourses = null; /** @@ -14,10 +29,10 @@ let currentCourses = null; * * - `id`: Unique identifier for the course. * - `line`: Line number. - * - `nextStop`: Identifier of the next stop of the course. - * - `arrivalTime`: Timestamp at which the vehicle is predicted to arrive - * to the next stop. * - `finalStop`: The final stop to which the course is headed. + * - `nextPassings`: Next passings of the vehicle, sorted by increasing + * arrival time, containing both the stop identifier (`stopId`) and the + * expected arrival timestamp (`arrivalTime`). * * @return Mapping from active course IDs to information about each course. */ @@ -42,6 +57,13 @@ const getCourses = () => new Promise((res, rej) => if (!util.isObject(entry)) { + // End of courses information stream. Sort next stops by increasing + // arrival time in each course then save result in memory cache + for (let course of Object.values(courses)) + { + course.nextPassings.sort(passingCompare); + } + currentCourses = courses; res(currentCourses); return; @@ -49,6 +71,7 @@ const getCourses = () => new Promise((res, rej) => if ('lastUpdate' in entry) { + // Metadata header lastUpdate = entry.lastUpdate; nextUpdate = entry.nextUpdate; return; @@ -57,7 +80,7 @@ const getCourses = () => new Promise((res, rej) => const { course: id, routeShortName: line, - stopId: nextStop, + stopId, destArCode: finalStop, } = entry; @@ -65,14 +88,14 @@ const getCourses = () => new Promise((res, rej) => if (!(id in courses)) { - courses[id] = {id, line, nextStop, arrivalTime, finalStop}; + courses[id] = { + id, line, finalStop, + nextPassings: [{stopId, arrivalTime}], + }; } - else if (arrivalTime < courses[id].arrivalTime) + else { - // The stop where the next passing is soonest is assumed - // to be the next stop - courses[id].nextStop = nextStop; - courses[id].arrivalTime = arrivalTime; + courses[id].nextPassings.push({stopId, arrivalTime}); } }); });