Last active
March 18, 2025 22:02
-
-
Save artem-ye/66eebdebd975f176c639c0e3c736618e to your computer and use it in GitHub Desktop.
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
| const data = `city,population,area,density,country | |
| Shanghai,24256800,6340,3826,China | |
| Delhi,16787941,1484,11313,India | |
| Lagos,16060303,1171,13712,Nigeria | |
| Istanbul,14160467,5461,2593,Turkey | |
| Tokyo,13513734,2191,6168,Japan | |
| Sao Paulo,12038175,1521,7914,Brazil | |
| Mexico City,8874724,1486,5974,Mexico | |
| London,8673713,1572,5431,United Kingdom | |
| New York City,8537673,784,10892,United States | |
| Bangkok,8280925,1569,5279,Thailand`; | |
| const curry = (fn) => (...args) => { | |
| return (args.length < fn.length) ? curry(fn.bind(null, ...args)) : fn(...args); | |
| }; | |
| const compose = (...fns) => (arg) => fns.reduceRight((arg, fn) => fn(arg), arg); | |
| const DENSITY = 3; | |
| const ADD_DENSITY = 5; | |
| const parse = (data) => { | |
| const parseRows = (data) => data.split('\n'); | |
| const cutHead = (table) => table.slice(1); | |
| const cutTail = (table) => table.slice(0, -1); | |
| const parseCols = (table) => table.map((row) => row.split(',')); | |
| const process = compose(parseCols, cutTail, cutHead, parseRows); | |
| return process(data); | |
| }; | |
| const print = (table) => { | |
| const padEnd = curry((padding, s) => String(s).padEnd(padding)); | |
| const padStart = curry((padding, s) => String(s).padStart(padding)); | |
| const meta = Object.entries({ | |
| 0: padEnd(18), | |
| 1: padStart(10), | |
| 2: padStart(8), | |
| 3: padStart(8), | |
| 4: padStart(18), | |
| 5: padStart(6), | |
| }); | |
| const format = (row) => meta.reduce((acc, [i, fn]) => acc + fn(row[i]), ''); | |
| const printRow = (s) => console.log(s); | |
| table.map(format).map(printRow); | |
| }; | |
| const prepare = (table) => { | |
| const calcDensity = (table) => { | |
| const max = (acc, row) => Math.max(acc, parseInt(row[DENSITY])); | |
| const maxDensity = table.reduce(max, 0); | |
| const percent = (v) => Math.round((v * 100) / maxDensity); | |
| const addDensityCol = (row) => row.concat(percent(row[DENSITY])); | |
| return table.map(addDensityCol); | |
| }; | |
| const sort = (table) => { | |
| return table.sort((r1, r2) => r2[ADD_DENSITY] - r1[ADD_DENSITY]); | |
| }; | |
| const composed = compose(sort, calcDensity); | |
| return composed(table); | |
| }; | |
| const process = compose(print, prepare, parse); | |
| process(data || []); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment