Last active
November 21, 2021 17:12
-
-
Save brycetshaw/90c728cd3942d8e7d20a963366ed6a25 to your computer and use it in GitHub Desktop.
A script to make concurrent network requests!
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
const fetch = require('node-fetch'); | |
const queryString = (year, goals, page) => { | |
const rootUrl = 'https://jsonmock.hackerrank.com'; | |
const queryString = `/api/football_matches?year=${year}&team1goals=${goals}&team2goals=${goals}&page=${page}`; | |
return rootUrl + queryString; | |
} | |
async function getNumOfGamesFromPage(year, goals, page) { | |
const response = await fetch(queryString(year, goals, page)) | |
.catch(err => console.log("get error " + err.message)); | |
const json = await response.json(); | |
if (page === 0) { | |
return [json.data.length, json.total_pages]; | |
} else { | |
return json.data.length; | |
} | |
} | |
async function getTiesCountByNumberOfGoals(year, goals) { | |
const [gamesOnFirstPage, numberOfPages] = await getNumOfGamesFromPage(year, goals, 0); | |
const pageArray = Array.from(Array(numberOfPages).keys()).filter((e) => e !== 0); | |
return Promise.all( | |
[ | |
gamesOnFirstPage, | |
...pageArray.map(page => getNumOfGamesFromPage(year, goals, page)) | |
]) | |
).then(data => data.reduce((x, y) => x + y, 0) || 0); | |
} | |
async function getNumDraws(year) { | |
const arrayOfScores = Array.from(Array(11).keys()); | |
return Promise.all(arrayOfScores.map(item => getTiesCountByNumberOfGoals(year, item))) | |
.then(drawsCountForEachScore => { | |
return drawsCountForEachScore.reduce((x, y) => x + y, 0); | |
}) | |
} | |
async function main() { | |
const year = 2011; | |
const result = await getNumDraws(year); | |
console.log(`In ${year}, a total of ${result} games ended in a draw`); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment