random-bunny/index.js

39 lines
908 B
JavaScript
Raw Normal View History

2020-12-20 19:39:03 +00:00
const fetch = require('node-fetch');
2016-04-27 20:06:24 +01:00
2021-01-13 21:08:47 +00:00
const sortable = [
2020-12-20 19:39:03 +00:00
'new',
'hot',
'top'
]
2016-04-27 20:06:24 +01:00
2020-12-20 19:39:03 +00:00
function randomBunny(subreddit, sortBy, cb) {
if (!sortable.includes(sortBy)) sortBy = 'hot';
2016-04-27 20:06:24 +01:00
2020-12-20 19:39:03 +00:00
fetch(`https://www.reddit.com/r/${subreddit}/${sortBy}.json`).then(res => {
res.json().then(res => {
const data = res.data.children;
const size = data.length;
2016-04-27 20:06:24 +01:00
2020-12-20 19:39:03 +00:00
let found = false;
2016-04-27 20:06:24 +01:00
2020-12-20 19:39:03 +00:00
while (!found) {
const random = getRandom(0, size - 1);
2016-04-27 20:06:24 +01:00
2020-12-20 19:39:03 +00:00
const image = data[random].data['url'];
const title = data[random].data['title'];
2016-04-28 16:31:41 +01:00
2020-12-20 19:39:03 +00:00
if (image.includes('.jpg')) {
found = true;
cb(image, title);
}
2016-04-29 03:23:21 +01:00
}
});
2020-12-20 19:39:03 +00:00
});
2016-04-29 03:23:21 +01:00
}
2020-12-20 19:39:03 +00:00
function getRandom(min, max) {
return Math.floor((Math.random() * max) + min);
2016-04-28 16:31:41 +01:00
}
2021-01-13 21:08:47 +00:00
module.exports = randomBunny;