Created
July 15, 2022 12:13
-
-
Save kadiks/930f60b96239375cdfcb8857ab75f6e8 to your computer and use it in GitHub Desktop.
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
// Related to François' question on this video: https://www.youtube.com/watch?v=ThcV5bW62nc | |
const generateQuestion = (countries) => { | |
const randomIndex = Math.floor(Math.random() * countries.length); | |
const country = countries[randomIndex]; | |
const possibilities = []; | |
const selectedIndexes = []; // set of indexes of countries that are selected | |
while (possibilities.length < 3) { | |
const randomIndex = Math.floor(Math.random() * countries.length); | |
// if the random index is not in the selected indexes, add it to the possibilities | |
if (selectedIndexes.indexOf(randomIndex) === -1) { | |
const country = countries[randomIndex]; | |
possibilities.push(country.name); | |
selectedIndexes.push(randomIndex); | |
} | |
} | |
possibilities.push(country.name); | |
possibilities.sort((a, b) => { | |
return a.charCodeAt(0) - b.charCodeAt(0); | |
}); | |
const question = { | |
flag: country.flag, | |
answer: country.name, | |
possibilities, | |
}; | |
return question; | |
}; | |
// END | |
// only for testing and see that it actuall works | |
const getCountries = () => { | |
console.log("Loading countries..."); | |
console.log("This may take some time"); | |
return fetch("https://restcountries.com/v2/all") | |
.then((response) => response.json()) | |
.then((data) => data) | |
.catch((error) => console.log(error)); | |
}; | |
getCountries() | |
.then((countries) => { | |
const question = generateQuestion(countries); | |
console.log(question); | |
}) | |
.catch((error) => console.log(error)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment