Random Number Generator Based on Internet Speed
const http = require('http');
const https = require('https');
// DON'T JUDGE, THIS WAS MADE FOR A CHALLENGE.
class InternetRandom {
constructor(url, timeout) {
if (url && !url.startsWith('http:') && !url.startsWith('https:'))
throw new Error('Bad URL');
this.url = url || 'http://speedtest.tele2.net/1000GB.zip';
this.timeout = timeout || 2000;
this.client = this.url.startsWith('https') ? https : http;
this.running = false;
this.everRan = false;
this.request = null;
this.data = [];
}
start() {
if (this.running)
throw new Error('Already running!');
this.everRan = true;
this.running = true;
this.request = this.client.request(this.url, res => {
let last = Math.random() * Date.now();
res.on('data', chunk => {
this.data.push(this.random(Date.now() - last));
last = Date.now();
});
res.on('end', () => {
this.running = false;
});
});
this.request.end();
}
async read() {
if (!this.everRan)
this.start();
if (this.data.length < 1) {
if (!this.running) {
throw new Error('Generator exhausted');
} else {
let time = 0;
while (time < this.timeout) {
await this.sleep(100);
if (this.data.length > 0)
return this.data.shift();
time = time + 100;
}
throw new Error('Timeout occurred');
}
}
return this.data.shift();
}
async stop() {
this.request.abort();
}
isExhausted() {
return this.data.length < 1 && !this.running && this.everRan;
}
// https://codebottle.io/s/14f16d6577
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// https://stackoverflow.com/a/19303725/2164304
random(seed) {
const x = Math.sin(seed) * 10000;
return x - Math.floor(x);
}
}
This was made for a Programming Challenges Telegram group.
- Don't take this seriously.
- Never use this anywhere.
- Don't hate me.