This repository has been archived by the owner on Nov 16, 2021. It is now read-only.
forked from harpreetkhalsagtbit/country-state-city
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
58 lines (54 loc) · 1.61 KB
/
index.ts
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
import countryList from './lib/country.json';
import stateList from './lib/state.json';
import cityList from './lib/city.json';
import { ICountry, ICity, IState } from './src/interface';
export { ICountry, ICity, IState } from './src/interface';
const _findEntryByCode = (source: any, code: string) => {
if (code && source != null) {
const codex = source.findIndex((c: any) => {
return c.isoCode === code;
});
return codex !== -1 ? source[codex] : '';
}
return '';
};
const compare = (a: any, b: any) => {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
};
export default {
getStatesOfCountry(countryCode: string): IState[] {
const states = stateList.filter((value) => {
return value.countryCode === countryCode;
});
return states.sort(compare);
},
getCitiesOfState(countryCode: string, stateCode: string): ICity[] {
const cities = cityList.filter((value: { countryCode: string; stateCode: string; }) => {
return value.countryCode === countryCode && value.stateCode === stateCode;
});
return cities.sort(compare);
},
getCitiesOfCountry(countryCode: string): ICity[] {
const cities = cityList.filter((value: { countryCode: string; }) => {
return value.countryCode === countryCode;
});
return cities.sort(compare);
},
getAllCountries(): ICountry[] {
return countryList;
},
getAllStates(): IState[] {
return stateList;
},
getAllCities(): ICity[] {
return cityList;
},
getCountryByCode(isoCode: string): ICountry {
return _findEntryByCode(countryList, isoCode);
},
getStateByCode(isoCode: string): IState {
return _findEntryByCode(stateList, isoCode);
},
};