Last active
November 6, 2022 19:48
-
-
Save jordan-bravo/7dcd224c9a4015a51453ede895febabd to your computer and use it in GitHub Desktop.
Finest Food Outlets Using Http Module In NodeJS
This file contains 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
const https = require('https'); | |
const finestFoodOutlet = async (city, votes) => { | |
const myUrl = 'https://jsonmock.hackerrank.com/api/food_outlets?page='; | |
let pageNum = 1; | |
// construct http GET request | |
const httpGet = (url) => { | |
return new Promise((resolve, reject) => { | |
https | |
.get(url, (res) => { | |
res.setEncoding('utf8'); | |
let body = ''; | |
res.on('data', (chunk) => (body += chunk)); | |
res.on('end', () => resolve(body)); | |
}) | |
.on('error', reject); | |
}); | |
}; | |
const getTheData = async (_city, _votes) => { | |
// get the total number of pages | |
const responseJson = await httpGet(myUrl + 1); | |
const responseParsed = JSON.parse(responseJson); | |
const totalPages = responseParsed.total_pages; | |
// collect data from each page | |
let allPages = []; | |
for (pageNum; pageNum <= totalPages; pageNum++) { | |
const resp = await httpGet(myUrl + pageNum); | |
for (let i = 0; i < 10; i++) { | |
allPages.push(JSON.parse(resp).data[i]); | |
} | |
} | |
return allPages; | |
}; | |
getTheData(city, votes).then((allResults) => { | |
// filter results based on min number of votes | |
const filteredResults = allResults.filter( | |
(item) => item.city === city && item.user_rating.votes >= votes | |
); | |
// sort results by rating, descending | |
const sortedResults = filteredResults.sort((a, b) => { | |
if (a.user_rating.average_rating < b.user_rating.average_rating) | |
return 1; | |
else if ( | |
a.user_rating.average_rating > b.user_rating.average_rating | |
) | |
return -1; | |
else { | |
if (a.user_rating.votes < b.user_rating.votes) return 1; | |
else if (a.user_rating.votes > b.user_rating.votes) return -1; | |
else return 0; | |
} | |
}); | |
console.log('sortedResults: ', sortedResults); | |
// get winning restaurant name | |
const winningRestaurant = sortedResults[0].name; | |
console.log('Winning Restaurant: ', winningRestaurant); | |
return winningRestaurant; | |
}); | |
}; | |
// call the function | |
finestFoodOutlet('Miami', 9000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment