Created
April 2, 2023 04:07
-
-
Save cheekybastard/4db854ea6db7af89ae04b7cf6ebbcb72 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
// https://rxjs.dev/api | |
const { from, timer } = require('rxjs'); | |
const { last, map, catchError, switchMap } = require('rxjs/operators'); | |
// https://danfo.jsdata.org/ | |
const dfd = require('danfojs-node'); | |
let latestBlocktime = 2.2; | |
function getBlocktime() { | |
return from(dfd.readCSV('https://polygonscan.com/chart/blocktime?output=csv')).pipe( | |
catchError((error) => { | |
console.error(error); | |
return from(Promise.resolve(null)); | |
}), | |
map((df) => { | |
const value = parseFloat(df['Value'].tail(1).values[0]); | |
if (isNaN(value)) { | |
throw new Error('Latest value is NaN'); | |
} | |
latestBlocktime = value; | |
return latestBlocktime; | |
}), | |
last() | |
); | |
} | |
function main() { | |
// update every 5mins | |
timer(0, 5 * 60 * 1000) | |
.pipe(switchMap(() => getBlocktime())) | |
.subscribe({ | |
next: (latestFloatValue) => { | |
console.log('return val:', latestFloatValue); | |
console.log('global val:', latestBlocktime); | |
}, | |
error: (error) => { | |
console.error(error); | |
}, | |
complete: () => { | |
console.log('Done!'); | |
}, | |
}); | |
} | |
main(); | |
// Export latestBlocktime as a global variable | |
global.latestBlocktime = () => latestBlocktime; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment