Create a gist now

Instantly share code, notes, and snippets.

@dimaip /shri.js forked from verkholantsev/shri.js
Last active Aug 29, 2015

What would you like to do?
Задание на ШРИ 2015
/**
* Реализация API, не изменяйте ее
* @param {string} url
* @param {function} callback
*/
function getData(url, callback) {
var RESPONSES = {
'/countries': [
{name: 'Cameroon', continent: 'Africa'},
{name :'Fiji Islands', continent: 'Oceania'},
{name: 'Guatemala', continent: 'North America'},
{name: 'Japan', continent: 'Asia'},
{name: 'Yugoslavia', continent: 'Europe'},
{name: 'Tanzania', continent: 'Africa'}
],
'/cities': [
{name: 'Bamenda', country: 'Cameroon'},
{name: 'Suva', country: 'Fiji Islands'},
{name: 'Quetzaltenango', country: 'Guatemala'},
{name: 'Osaka', country: 'Japan'},
{name: 'Subotica', country: 'Yugoslavia'},
{name: 'Zanzibar', country: 'Tanzania'},
],
'/populations': [
{count: 138000, name: 'Bamenda'},
{count: 77366, name: 'Suva'},
{count: 90801, name: 'Quetzaltenango'},
{count: 2595674, name: 'Osaka'},
{count: 100386, name: 'Subotica'},
{count: 157634, name: 'Zanzibar'}
]
};
setTimeout(function () {
var result = RESPONSES[url];
if (!result) {
return callback('Unknown url');
}
callback(null, result);
}, Math.round(Math.random * 1000));
}
/**
* Ваши изменения ниже
*/
/**
* Комментарии к коду будем писать по-английски, т.к. код могут в дальнейшем
* обслуживать не только русскоговорящие разработчики.
*/
/**
* The problem with original implementation was that it created new callbacks
* in for loop, which does not create new scope in JS.
* As a minimal viable fix without altering a lot of code,
* let's use IIFE to create a new scope.
*
* In addition to that, let's separate the logic for retriving results data
* into separate function with a callback that would fire once we have all the data,
* without leaking anything to global scope.
*/
/*
* Our custom API to fetch all data
*
* @param {function} Callback that fires when all responses where gathered
*/
function getCompleteData(resultsCallback) {
var requests = ['/countries', '/cities', '/populations'];
var responses = {};
for (i = 0; i < 3; i++) {
(function(){
var request = requests[i];
var callback = function (error, result) {
if (!error) {
responses[request] = result;
var l = [];
for (K in responses)
l.push(K);
if (l.length == 3) {
resultsCallback(responses);
}
}
};
getData(request, callback);
}());
}
}
/**
* Original code to calculate population of Africa
*/
function countPopulationInAfricanCities(responses) {
var c = [], cc = [], p = 0;
for (i = 0; i < responses['/countries'].length; i++) {
if (responses['/countries'][i].continent === 'Africa') {
c.push(responses['/countries'][i].name);
}
}
for (i = 0; i < responses['/cities'].length; i++) {
for (j = 0; j < c.length; j++) {
if (responses['/cities'][i].country === c[j]) {
cc.push(responses['/cities'][i].name);
}
}
}
for (i = 0; i < responses['/populations'].length; i++) {
for (j = 0; j < cc.length; j++) {
if (responses['/populations'][i].name === cc[j]) {
p += responses['/populations'][i].count;
}
}
}
console.log('Total population in African cities: ' + p);
}
getCompleteData(countPopulationInAfricanCities);
/**
* Prompts for country and calculates population for all cities in that country
*/
function countPopulationInGivenCountry(responses) {
var lookupCountry = prompt("Введите название страны", "Japan");
var p = 0;
for (i = 0; i < responses['/cities'].length; i++) {
if (responses['/cities'][i].country === lookupCountry) {
for (j = 0; j < responses['/populations'].length; j++) {
p += responses['/populations'][j].count;
}
}
}
console.log('Total population in ' + lookupCountry + ' cities: ' + p);
}
getCompleteData(countPopulationInGivenCountry);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment