-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
61 lines (57 loc) · 1.13 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
'use strict';
const countries = require('./data/countries.json');
function isObject(obj) {
return obj !== null && typeof obj === 'object';
}
function isValidKey(key) {
const validKeys = [
'name',
'a2',
'a3',
'num',
'itu',
'gec',
'ioc',
'fifa',
'ds',
'wmo',
'gaul',
'marc',
'dial',
'independent'
];
if(validKeys.indexOf(key) > -1) {
return true;
}
else {
return false;
}
}
function findCountry(searchTerm, exact) {
if(isObject(searchTerm)){
let keyOriginal = Object.keys(searchTerm)[0];
let key = new String(Object.keys(searchTerm)[0]).toLowerCase();
let value = new String(searchTerm[keyOriginal]).toLowerCase();
if(isValidKey(key)){
for(let i = 0; i < countries.length; i++){
let searchedKey = countries[i][key].toLowerCase();
if(exact && searchedKey === value) {
return countries[i];
}
if(!exact && searchedKey.indexOf(value) > -1){
return countries[i];
}
}
return null;
}
else {
throw new Error('invalid key');
}
}
else {
throw new Error('invalid search term, should be an object with a single key:value pair');
}
}
module.exports = {
findCountry
};