Skip to content

Instantly share code, notes, and snippets.

@frantzmiccoli
Last active August 29, 2015 14:05
Show Gist options
  • Save frantzmiccoli/8e65d5791cb5827e3f6e to your computer and use it in GitHub Desktop.
Save frantzmiccoli/8e65d5791cb5827e3f6e to your computer and use it in GitHub Desktop.
Splitting world's biggest urban area between rich and poor to compute a sum of those population.
// Run me on http://en.wikipedia.org/wiki/List_of_metropolitan_areas_by_population
// from http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery
var getTextNodesIn = function($el) {
return $($el.find(":not(iframe)").addBack().contents().filter(function() {
return this.nodeType == 3;
}).get(0)).text();
};
var rowsSelector = '#bodyContent .sortable.wikitable.jquery-tablesorter tr',
$rows = $(rowsSelector),
cityNameSelector = 'td:eq(0) a',
cityPopSelector = 'td:eq(4)',
cityAltPopSelector = 'td:eq(3)',
cityCountrySelector = 'td:eq(1) a',
citiesData = [],
richCountries = ['United States', 'France', 'South Korea', 'Italy', 'Spain', 'Germany',
'United Kingdom', 'Japan', 'Russia', 'Singapore'],
richSum = 0,
poorSum = 0;
$rows.each(function(_, item) {
var $item = $(item),
name = getTextNodesIn($item.find(cityNameSelector)),
$pop = $item.find(cityPopSelector),
pop = getTextNodesIn($pop).replace(/,/g, ''),
validPop = !(typeof(pop) === 'undefined') && (pop !== '');
if (!validPop) {
$pop = $item.find(cityAltPopSelector),
pop = getTextNodesIn($pop).replace(/,/g, ''),
validPop = !(typeof(pop) === 'undefined') && (pop !== '');
}
if (!validPop) {
return true;
}
var $country = $item.find(cityCountrySelector),
country = $country.attr('title'),
validCountry = !(typeof(country) === 'undefined') && (country !== '');
if (!validCountry) {
return true;
}
if (richCountries.indexOf(country) !== -1) {
richSum += new Number(pop);
} else {
poorSum += new Number(pop);
console.log(country);
}
var cityData = {
name: name,
pop: pop,
country: country,
};
citiesData.push(cityData);
});
console.log(richSum);
console.log(poorSum);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment