Last active
July 26, 2021 20:43
-
-
Save theRemix/c2dcbd154fcf60a0f0954944f5670683 to your computer and use it in GitHub Desktop.
big-waves.js
This file contains 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 { Router } = require('express') | |
const fetch = require('node-fetch') | |
const app = Router() | |
const noaaUrl = sid => `https://www.ndbc.noaa.gov/data/realtime2/${sid}.txt` | |
const units = 'm' | |
const omitComments = waveRow => !waveRow.startsWith('#') | |
const omitEmptyRow = waveRow => waveRow.length > 0 | |
const rowsWithWVHT = waveRow => waveRow.WVHT !== 'MM' | |
const waveFormat = waveRow => ({ | |
time: rowToTime(waveRow), | |
height: `${waveRow.WVHT}${units}` | |
}) | |
const rowToTime = waveRow => `${waveRow.YY}-${waveRow.MM}-${waveRow.DD}` | |
// [YY, MM, DD, ...] | |
const waveRowToHeaders = headers => | |
headers = headers.substr(1) // remove the leading # | |
.split(/\s+/) | |
// input: [2020, 08, ...] | |
// output: { YY: 2020, MM: 08, ... } | |
// mapping function -----------v | |
const waveRowToObj = headers => waveRow => | |
headers.reduce((obj, _header, idx) => ({ | |
...obj, | |
[headers[idx]]: waveRow[idx] | |
}), {}) | |
// mapping function ----------------v | |
const highestWaves = (headers, n) => waveData => | |
waveData | |
.split('\n') | |
.filter(omitComments) | |
.filter(omitEmptyRow) | |
.map(row => row.split(/\s+/)) | |
.map(waveRowToObj(headers)) | |
.filter(rowsWithWVHT) | |
.sort((a,b) => parseFloat(b.WVHT) - parseFloat(a.WVHT)) | |
.slice(0,n) | |
.map(waveFormat) | |
// takes sid and n, returns [{ time, height }] or {error} | |
app.get('/', (req, res) => { | |
const { sid, n } = req.query | |
// validation | |
if(sid === undefined){ | |
const error = 'Missing required param: sid' | |
console.log(error) | |
return res.json({error}) | |
} | |
if(n === undefined){ | |
const error = 'Missing required param: n' | |
console.log(error) | |
return res.json({error}) | |
} | |
fetch(noaaUrl(sid)) | |
.then(response => response.text()) | |
.then(response => { | |
const waveHeaders = waveRowToHeaders(response.split('\n')[0]) | |
return highestWaves(waveHeaders, n)(response) | |
}) | |
.then(res.json.bind(res)) | |
.catch(error => { | |
console.error(error) | |
res.json({ error }) | |
}) | |
}) | |
module.exports = app |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
aoeu