Skip to content

Instantly share code, notes, and snippets.

@theRemix
Last active July 26, 2021 20:43
Show Gist options
  • Save theRemix/c2dcbd154fcf60a0f0954944f5670683 to your computer and use it in GitHub Desktop.
Save theRemix/c2dcbd154fcf60a0f0954944f5670683 to your computer and use it in GitHub Desktop.
big-waves.js
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
@theRemix
Copy link
Author

theRemix commented Jul 22, 2021

aoeu

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment