forked from ipetropolsky/js-part-1
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
252 lines (204 loc) · 7.79 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/* eslint-disable no-await-in-loop */
async function getData(url) {
// https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
redirect: 'follow',
});
return response.json();
}
async function loadCountriesData() {
const countries = await getData('https://restcountries.com/v3.1/all?fields=name&fields=cca3&fields=area');
return countries.reduce((result, country) => {
result[country.cca3] = country;
return result;
}, {});
}
class MockApi {
async init(url) {
const countries = await getData(url);
this._borders = {};
for (const { cca3, borders } of countries) {
this._borders[cca3] = borders;
}
}
async getBorders(code) {
return this._borders[code];
}
}
// Функция для прямого запроса данных по каждой стране
async function getBordersFromApi(code) {
const data = await getData(`https://restcountries.com/v3.1/alpha/${code}?fields=borders`);
return data.borders;
}
async function getBordersForAll(codes, getBorders) {
const bordersArray = await Promise.all(codes.map(getBorders));
const bordersMap = {};
for (let i = 0; i < codes.length; i++) {
const code = codes[i];
const borders = bordersArray[i];
bordersMap[code] = borders;
}
return bordersMap;
}
async function calculateRoute(fromCode, toCode, getBorders) {
async function step(routes, visited, queriesCount, getBorders) {
const codes = routes.map((route) => route[route.length - 1]);
const codesToCheck = [...new Set(codes)];
codesToCheck.forEach((code) => visited.add(code));
queriesCount += codesToCheck.length;
const bordersMap = await getBordersForAll(codesToCheck, getBorders);
const newRoutes = [];
for (let i = 0; i < routes.length; i++) {
const route = routes[i];
const code = route[route.length - 1];
const borders = bordersMap[code].filter((border) => !visited.has(border));
borders.forEach((border) => {
newRoutes.push([...route, border]);
});
}
return [newRoutes, queriesCount];
}
function findCommon(routesForward, routesBackward) {
const codesForward = routesForward.map((route) => route[route.length - 1]);
const codesBackward = routesBackward.map((route) => route[route.length - 1]);
const common = [];
codesForward.forEach((code) => {
if (codesBackward.includes(code)) {
common.push(code);
}
});
return common;
}
function combineRoutes(routesForward, routesBackward) {
const common = findCommon(routesForward, routesBackward);
routesForward = routesForward.filter((route) => common.includes(route[route.length - 1]));
routesBackward = routesBackward.filter((route) => common.includes(route[route.length - 1]));
const routes = [];
for (const routeForward of routesForward) {
for (const routeBackward of routesBackward) {
if (routeForward[routeForward.length - 1] === routeBackward[routeBackward.length - 1]) {
routes.push([...routeForward.slice(0, -1), ...routeBackward.reverse()]);
}
}
}
return routes;
}
let queriesCount = 0;
const visitedForward = new Set([fromCode]);
const visitedBackward = new Set([toCode]);
let routesForward = [[fromCode]];
let routesBackward = [[toCode]];
let isDone = false;
let isForwardMode = true;
while (!isDone && routesForward.length && routesBackward.length) {
try {
if (isForwardMode && routesForward.length) {
[routesForward, queriesCount] = await step(routesForward, visitedForward, queriesCount, getBorders);
} else if (routesBackward.length) {
[routesBackward, queriesCount] = await step(routesBackward, visitedBackward, queriesCount, getBorders);
}
} catch {
return {
hasError: true,
queriesCount,
routes: [],
};
}
isDone = findCommon(routesForward, routesBackward).length > 0;
isForwardMode = !isForwardMode;
}
const routes = combineRoutes(routesForward, routesBackward);
return {
hasError: false,
queriesCount,
routes,
};
}
function getCodeByCountryName(name, countriesData) {
for (const code in countriesData) {
if (countriesData[code].name.common === name) {
return code;
}
}
return null;
}
const form = document.getElementById('form');
const fromCountry = document.getElementById('fromCountry');
const toCountry = document.getElementById('toCountry');
const countriesList = document.getElementById('countriesList');
const submit = document.getElementById('submit');
const output = document.getElementById('output');
const requestMode = document.getElementById('request-mode');
function blockForm() {
fromCountry.disabled = true;
toCountry.disabled = true;
submit.disabled = true;
}
function unblockForm() {
fromCountry.disabled = false;
toCountry.disabled = false;
submit.disabled = false;
}
function addStringToOutput(string) {
const info = document.createElement('p');
info.textContent = string;
output.append(info);
}
(async () => {
blockForm();
output.textContent = 'Loading…';
const countriesData = await loadCountriesData();
output.textContent = '';
// Заполняем список стран для подсказки в инпутах
Object.keys(countriesData)
.sort((a, b) => countriesData[b].area - countriesData[a].area)
.forEach((code) => {
const option = document.createElement('option');
option.value = countriesData[code].name.common;
countriesList.appendChild(option);
});
unblockForm();
form.addEventListener('submit', async (event) => {
event.preventDefault();
console.time('Calculation done in ');
const fromName = fromCountry.value;
const toName = toCountry.value;
const mode = requestMode.value;
if (!fromName || !toName || fromName === toName) {
return;
}
blockForm();
output.textContent = `Calculating route from ${fromName} to ${toName}...`;
let getBorders;
if (mode === 'Every request goes to API') {
getBorders = getBordersFromApi;
} else {
const mockApi = new MockApi();
await mockApi.init('https://restcountries.com/v3.1/all?fields=cca3&fields=borders');
getBorders = mockApi.getBorders.bind(mockApi);
}
const fromCode = getCodeByCountryName(fromName, countriesData);
const toCode = getCodeByCountryName(toName, countriesData);
const { hasError, queriesCount, routes } = await calculateRoute(fromCode, toCode, getBorders);
output.textContent = '';
if (hasError) {
addStringToOutput('Error on request. May be too far away? ┗|`O′|┛');
} else if (!routes.length) {
addStringToOutput('No such routes ⚆_⚆');
} else {
routes.forEach((route) => {
const message = `${route.map((code) => countriesData[code].name.common).join(' → ')} (${
route.length - 1
} borders)`;
addStringToOutput(message);
});
}
addStringToOutput(`Done in ${queriesCount} requests`);
console.timeEnd('Calculation done in ');
unblockForm();
});
})();