|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// FP paradigm: |
| 4 | +// 1. Equations instead of control flow |
| 5 | +// 2. Lazy calculations |
| 6 | +// 3. Parallel execution ready |
| 7 | +// 4. Recursion instead of loops |
| 8 | +// 5. Immutability, no state |
| 9 | +// 6. No variables, no side effects |
| 10 | +// 7. Math model |
| 11 | + |
| 12 | +const fs = require('fs'); |
| 13 | + |
| 14 | +const proportion = (max, val) => Math.round(val * 100 / max); |
| 15 | +const compose = (...funcs) => x => funcs.reduce((x, fn) => fn(x), x); |
| 16 | + |
| 17 | +const cellPad = (i, s, width) => (i ? s.padStart(width) : s.padEnd(width)); |
| 18 | +const cellWidth = i => [18, 10, 8, 8, 18, 6][i]; |
| 19 | + |
| 20 | +const renderCell = (cell, i) => cellPad(i, cell + '', cellWidth(i)); |
| 21 | +const renderRow = row => row.map(renderCell).join(''); |
| 22 | +const renderTable = table => table.map(renderRow).join('\n'); |
| 23 | + |
| 24 | +const densityCol = () => 3 |
| 25 | +const sortByDensity = table => table.sort( |
| 26 | + (row1, row2) => (row2[densityCol()] - row1[densityCol()]) |
| 27 | +) |
| 28 | +const calcColumn = (table, max) => table.map( |
| 29 | + row => (row.push(proportion(max, row[densityCol()])), row) |
| 30 | +); |
| 31 | +const calcProportion = table => calcColumn(table, table[0][densityCol()]); |
| 32 | + |
| 33 | +const parseTable = lines => lines.map(line => line.split(',')); |
| 34 | +const toLines = data => data.split('\n').filter((s, i) => i && s); |
| 35 | +const readFile = file => fs.readFileSync(file).toString(); |
| 36 | +const getDataset = compose(readFile, toLines, parseTable); |
| 37 | + |
| 38 | +const main = compose(getDataset, sortByDensity, calcProportion, renderTable); |
| 39 | + |
| 40 | +console.log(main('./cities.dat')); |
0 commit comments