-
-
Save crates/f51f5292d86b3978af605b58e857ef56 to your computer and use it in GitHub Desktop.
Code kata featuring: fetch, promises, array.sort, array.reduce, array.map
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment