From 1f860bc34f01d25f95310ea8cb7e2f27fff3283b Mon Sep 17 00:00:00 2001 From: Martin Fischer Date: Fri, 14 Mar 2025 06:32:43 +0100 Subject: refactor: introduce route and parseLatLon functions --- script.js | 56 +++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 39 insertions(+), 17 deletions(-) diff --git a/script.js b/script.js index d9086b8..ec32e6e 100644 --- a/script.js +++ b/script.js @@ -17,27 +17,49 @@ const LINKS = [ }, ]; -const latlon = location.hash.substring(1); -const [lat, lon] = latlon.split(','); - const heading = document.getElementById('heading'); -// TODO: listen on hashChange +route(); +// TODO: route on hashChange + +function route() { + const latLon = parseLatLon(location.hash.slice(1)); + + if (!latLon) { + heading.textContent = 'not yet implemented'; + } else { + const linkList = document.getElementById('links'); + document.getElementById('instructions').hidden = false; -if (isNaN(lat) || isNaN(lon)) { - heading.textContent = 'not yet implemented'; -} else { - const linkList = document.getElementById('links'); - document.getElementById('instructions').hidden = false; + document.title = 'Open location'; + heading.textContent = ''; - document.title = 'Open location'; + const [lat, lon] = latLon; - for (const link of LINKS) { - const li = document.createElement('li'); - const a = document.createElement('a'); - a.href = link.url.replace('{lat}', lat).replace('{lon}', lon); - a.textContent = link.label; - li.appendChild(a); - linkList.appendChild(li); + for (const link of LINKS) { + const li = document.createElement('li'); + const a = document.createElement('a'); + a.href = link.url.replace('{lat}', lat).replace('{lon}', lon); + a.textContent = link.label; + li.appendChild(a); + linkList.appendChild(li); + } + } +} + +function parseLatLon(text) { + if (text == '') { + return null; + } + + let [lat, lon] = text.split(','); + lat = parseFloat(lat); + lon = parseFloat(lon); + if (Number.isNaN(lat) || Number.isNaN(lon)) { + throw Error('failed to parse latitude or longitude'); + } + if (lat < -180 || lat > 180 || lon < -90 || lon > 90) { + throw Error('latitude or longitude are out of range'); } + return [lat, lon]; } -- cgit v1.2.3