Skip to content

Instantly share code, notes, and snippets.

@kdzwinel
Last active February 11, 2020 17:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kdzwinel/b08d36fb3a8f45748d35 to your computer and use it in GitHub Desktop.
Save kdzwinel/b08d36fb3a8f45748d35 to your computer and use it in GitHub Desktop.
Code kata featuring: fetch, promises, array.sort, array.reduce, array.map
// 1) fetch members of polish parlament (poslowie)
// 2) group them by occupation
// 3) sort occupations by number of members and occupation name
// 4) get top 5 entries
// 5) print result on the screen
(function() {
'use strict';
const POSLOWIE_ENDPOINT = 'https://api-v3.mojepanstwo.pl/dane/poslowie/';
fetch(POSLOWIE_ENDPOINT)
.then(response => response.json())
.then(data => data.Dataobject)
.then(sumByOccupation)
.then(occupationsMap => {
return occupationsMap
.sort(compareByCountAndName)
.slice(0, 5);
})
.then(printToScreen)
.catch(e => console.error(e));
function sumByOccupation(poslowie) {
return Array.from(
poslowie
.map(posel => posel.data['poslowie.zawod'])
.reduce((map, occupation) => {
const numberOfEntries = map.get(occupation) || 0;
return map.set(occupation, numberOfEntries + 1);
}, new Map())
).map(([occupation, count]) => {
return {occupation, count};
});
}
function compareByCountAndName(a, b) {
return b.count - a.count || (a.occupation).localeCompare(b.occupation);
}
function printToScreen(data) {
console.table(data);
}
})();
@kdzwinel
Copy link
Author

Sample output:

screen shot 2016-03-14 at 01 27 01

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment