forked from bhatvikrant/world-countries-capitals
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (60 loc) · 1.81 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
let data = require("./data/data.json");
const randomNum = () => {
return Math.floor(Math.random() * data.length);
};
// Get a random country
const getRandomCountry = () => {
let randNum = randomNum();
return data[randNum].country;
};
// Get data of N countries
const getNRandomCountriesData = count => {
let randomCountriesSet = new Set(); // to prevent duplicate countries
while (randomCountriesSet.size < count) {
let country = data[randomNum()];
randomCountriesSet.add(country); // adds a country to the Array
}
return Array.from(randomCountriesSet); // Returns the Array
};
// Helper function
const getCountriesByObject = (value, obj) => {
let resultArray = [];
value = value.toLowerCase();
object = obj;
data.forEach(item => {
item[object] = item[object];
if (item[object] && item[object].includes(value)) {
resultArray.push(item);
}
});
return resultArray;
};
// Get details of a country by the capital name
const getCountryDetailsByCapital = capital => {
return getCountriesByObject(capital, "capital");
};
// Get details of a country by the country name
const getCountryDetailsByName = country => {
return getCountriesByObject(country, "country");
};
// Get country details by the language spoken
const getCountriesByLanguage = languageSpoken => {
return getCountriesByObject(languageSpoken, "native_language");
};
// Get details of all countries
const getAllCountryDetails = () => {
return data;
};
// Get all countries Name
const getAllCountries = () => {
return data.map(({ country }) => country);
};
module.exports = {
getRandomCountry,
getNRandomCountriesData,
getCountryDetailsByCapital,
getCountryDetailsByName,
getAllCountryDetails,
getAllCountries,
getCountriesByLanguage
};