forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGooglePlacesUtils.ts
More file actions
52 lines (47 loc) · 2.18 KB
/
GooglePlacesUtils.ts
File metadata and controls
52 lines (47 loc) · 2.18 KB
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
type AddressComponent = {
longText: string;
shortText: string;
types: string[];
};
type FieldsToExtract = Record<string, Exclude<keyof AddressComponent, 'types'>>;
/**
* Finds an address component by type, and returns the value associated to key. Each address component object
* inside the addressComponents array has the following structure:
* [{
* longText: "New York",
* shortText: "New York",
* types: [ "locality", "political" ]
* }]
*/
function getAddressComponents(addressComponents: AddressComponent[], fieldsToExtract: FieldsToExtract): Record<string, string> {
const result: Record<string, string> = {};
Object.keys(fieldsToExtract).forEach((key) => (result[key] = ''));
addressComponents.forEach((addressComponent) => {
addressComponent.types.forEach((addressType) => {
if (!(addressType in fieldsToExtract) || !(addressType in result && result[addressType] === '')) {
return;
}
const value = addressComponent[fieldsToExtract[addressType]] ? addressComponent[fieldsToExtract[addressType]] : '';
result[addressType] = value;
});
});
return result;
}
type AddressTerm = {value: string};
type GetPlaceAutocompleteTermsResultKey = 'country' | 'state' | 'city' | 'street';
type GetPlaceAutocompleteTermsResult = Partial<Record<GetPlaceAutocompleteTermsResultKey, string>>;
/**
* Finds an address term by type, and returns the value associated to key. Note that each term in the address must
* conform to the following ORDER: <street, city, state, country>
*/
function getPlaceAutocompleteTerms(addressTerms: AddressTerm[]): GetPlaceAutocompleteTermsResult {
const fieldsToExtract: GetPlaceAutocompleteTermsResultKey[] = ['country', 'state', 'city', 'street'];
const result: GetPlaceAutocompleteTermsResult = {};
fieldsToExtract.forEach((fieldToExtract, index) => {
const fieldTermIndex = addressTerms.length - (index + 1);
result[fieldToExtract] = fieldTermIndex >= 0 ? addressTerms.at(fieldTermIndex)?.value : '';
});
return result;
}
export {getAddressComponents, getPlaceAutocompleteTerms};
export type {AddressComponent, FieldsToExtract, AddressTerm};