Last active
June 10, 2018 01:12
-
-
Save menxit/400552a7afc021340e10c58c8bd8759c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const https = require('https') | |
const haversine = (a, b) => { | |
const R = 6373044 | |
const { cos, sin, sqrt, PI, asin } = Math | |
const toRad = x => x * PI / 180 | |
const dLat = toRad(a.lat - a.lon) | |
const dLon = toRad(b.lat - b.lon) | |
const f = (sin(dLat / 2.0))**2 + cos(toRad(a.lon)) * cos(toRad(a.lat)) * (sin(dLon / 2.0))**2 | |
const c = 2 * R * asin(sqrt(f), sqrt(1 - f)) | |
return Math.round((R * c)/10**10) | |
} | |
const getAllStates = () => new Promise((resolve, reject) => { | |
const req = https.request({ | |
hostname: 'opensky-network.org', | |
port: 443, | |
path: '/api/states/all', | |
method: 'GET', | |
headers: { | |
'Content-Type': 'text/json' | |
} | |
}, res => { | |
res.setEncoding('utf8'); | |
let result = '' | |
res.on('data', chunk => result += chunk); | |
res.on('end', () => resolve(JSON.parse(result))) | |
}) | |
req.end() | |
}) | |
const challenge = async (source) => { | |
const { states } = await getAllStates() | |
return states | |
.filter(state => state[5] && state[6]) | |
.map(state => { | |
const destination = { lat: state[5], lon: state[6] } | |
const distance = haversine(source, destination) | |
return [ distance, state[1], state[5], state[6], state[7], state[2], state[0] ] | |
}) | |
.sort((a, b) => a[0] - b[0])[0] | |
} | |
challenge({ lat: 41.8902, lon: 12.4932 }).then(console.log) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment