Created
August 29, 2021 07:14
-
-
Save siddydutta/fa03e75b7bc6ca5adac08ef3ec0c1a9a to your computer and use it in GitHub Desktop.
HackerRank - JavaScript Basic Assessment - Country Codes
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
// HackerRank's NodeJS environment allows the `request` package. | |
const request = require('request'); | |
function fetch(url) { | |
return new Promise((resolve, reject) => { | |
request(url, function (error, response, body) { | |
if (error) | |
reject(error) | |
else | |
resolve(body) | |
}); | |
}); | |
} | |
async function getCountryName(countryCode) { | |
let pageNumber = 1; | |
let countryName = null; | |
while (countryName === null) { | |
let url = `https://jsonmock.hackerrank.com/api/countries?page=${pageNumber}`; | |
response = await fetch(url); | |
responseBody = JSON.parse(response); | |
responseBody.data.forEach((countryData) => { | |
if (countryData.alpha2Code === countryCode) | |
countryName = countryData.name; | |
}); | |
if (responseBody.total_pages == pageNumber++) | |
break; | |
} | |
if (countryName === null) { | |
throw new Error("Country code not found."); | |
} | |
return countryName; | |
} | |
getCountryName("AF").then((result) => { | |
console.log(result); | |
}); | |
getCountryName("ZW").then((result) => { | |
console.log(result); | |
}); | |
getCountryName("NaN").then((result) => { | |
console.log(result); | |
}).catch((error) => { | |
console.log(error.message); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment