From cfe7b5d78b7572afc55b480e3792119b14ccc5dc Mon Sep 17 00:00:00 2001 From: Vylpes Date: Fri, 29 Jan 2021 18:26:48 +0000 Subject: [PATCH] Comment Code --- index.js | 19 ++++++++++++++++++- package-lock.json | 2 +- package.json | 2 +- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/index.js b/index.js index 0082ee7..eaa2bce 100644 --- a/index.js +++ b/index.js @@ -1,27 +1,42 @@ +// Required Modules const fetch = require('node-fetch'); +// Valid sortBy names const sortable = [ 'new', 'hot', 'top' ] +// Main function function randomBunny(subreddit, sortBy, cb) { + // If the sortable list doesn't include sortBy, default to 'hot' if (!sortable.includes(sortBy)) sortBy = 'hot'; + // Fetch the json from reddit + // For example, if you're getting a random image from r/rabbits, sorted by new: + // https://www.reddit.com/r/rabbits/new.json fetch(`https://www.reddit.com/r/${subreddit}/${sortBy}.json`).then(res => { res.json().then(res => { + // Get the part of the json string which the data comes from const data = res.data.children; const size = data.length; + // Found is used for the while loop in order to break out of the loop. + // We need to loop as the json string will contain invalid data for what we need + // Specifically videos. let found = false; + // Loop until a valid image post is found while (!found) { + // Generate random number const random = getRandom(0, size - 1); + // Get variables from json to pass back const image = data[random].data['url']; const title = data[random].data['title']; + // If the post is a .jpg, send back the data and stop looping if (image.includes('.jpg')) { found = true; cb(image, title); @@ -31,8 +46,10 @@ function randomBunny(subreddit, sortBy, cb) { }); } +// Generate a random number function getRandom(min, max) { return Math.floor((Math.random() * max) + min); } -module.exports = randomBunny; +// Export Functions +module.exports = randomBunny; \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 3146de0..03134cb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,6 +1,6 @@ { "name": "random-bunny", - "version": "1.0.0", + "version": "20.0.0", "lockfileVersion": 1, "requires": true, "dependencies": { diff --git a/package.json b/package.json index a0804af..eca4a6a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "random-bunny", - "version": "1.0.0", + "version": "20.0.0", "description": "Get a random subreddit image url", "license": "MIT", "author": "Vylpes",