jubilee/server/reducers/directions.js
2018-10-12 16:19:55 +01:00

95 lines
2.6 KiB
JavaScript

const logger = require('log4js').getLogger('Directions 🔧');
const { get, isEmpty, has, uniq } = require('lodash');
const humanizeDuration = require('humanize-duration');
logger.level = 'debug';
const htmlTidy = /<(\/*?)(?!(em|p|br\s*\/|strong|h1|h2|h3))\w+?.+?>/gim;
function reduceEstDirections(body = '') {
if (body === '') return {};
// logger.debug(body);
const jBody = JSON.parse(body);
const obj = {};
const { ResultSet } = jBody;
const streets = [];
const steps = [];
if (has(ResultSet, 'Result')) {
const directions = get(ResultSet, 'Result.yahoo_driving_directions');
const route = get(directions, 'directions.route_leg');
obj.totalTime = parseFloat(get(directions, 'total_time'));
obj.totalTimeWithTraffic = parseFloat(get(directions, 'total_time_with_traffic'));
obj.readable = humanizeDuration((obj.totalTimeWithTraffic !== 0 ? obj.totalTimeWithTraffic : obj.totalTime) * 60 * 1000);
obj.timePercentage = ((obj.totalTime * ( obj.totalTimeWithTraffic / 100 )) + obj.totalTime) - 100;
if ( obj.totalTimeWithTraffic > (obj.totalTime * 1.75)) {
obj.traffic = 'heavy traffic';
obj.className = 'trafficHeavy';
}
else if ( obj.totalTimeWithTraffic > (obj.totalTime * 1.5)) {
obj.traffic = 'some traffic';
obj.className = 'trafficMedium';
}
else if ( obj.totalTimeWithTraffic > (obj.totalTime * 1.25)) {
obj.traffic = 'light traffic';
obj.className = 'trafficLight';
}
else {
obj.traffic = 'no traffic';
obj.className = 'trafficNone';
}
for (const item of route) {
if (item.hasOwnProperty('street')) {
const street = item.street.split(',');
if (street[0] !== '') streets.push(street[0]);
}
if (has(item, 'description')) {
steps.push(item.description);
}
}
obj.directions = steps;
obj.streets = uniq(streets);
}
return obj;
}
function reduceIncidents(body = '') {
if (body === '') return [];
const workObj = Object.assign({}, body);
const incidents = [];
const items = get(workObj, 'items');
for (const item of items) {
const title = item.title.split(' ');
incidents.push({
'title' : item.title,
'description': item.description,
'road' : title[0]
});
}
return incidents;
}
function combine(traffic, incidents) {
const workObj = Object.assign({ 'incidents':[] }, traffic);
for (const item of incidents)
if (workObj.streets.indexOf(item.road) > -1)
workObj.incidents.push(item);
return workObj;
}
module.exports = { reduceEstDirections, reduceIncidents, combine };