Created
February 25, 2022 18:45
-
-
Save Grohden/d094d6b52bbd7dffce29673370e60420 to your computer and use it in GitHub Desktop.
Script to pad CSV columns (for readability)
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 fs = require('fs'); | |
const filterMap = (list, map) => { | |
const mapped = []; | |
for (let i = 0; i < list.length; i++) { | |
const transformed = map(list[i]); | |
if (transformed) { | |
mapped.push(transformed); | |
} | |
} | |
return mapped; | |
}; | |
const readCSV = file => { | |
const csv = fs.readFileSync(require.resolve(file), 'utf8'); | |
return csv.split('\n'); | |
}; | |
const transformByLine = (file, format) => { | |
const csvSplit = readCSV(file); | |
return filterMap(csvSplit, line => line && format(line)); | |
}; | |
const parsedCSV = transformByLine( | |
'./my.csv', | |
line => line.split(',') | |
); | |
const padList = parsedCSV | |
.reduce((acc, line) => { | |
line.forEach((content, index) => { | |
if (!acc[index] || content.length > acc[index]) { | |
acc[index] = content.length; | |
} | |
}); | |
return acc; | |
}, []) | |
.map(pad => pad + 2); | |
const padByIndex = padList => line => { | |
return line | |
.map((item, index) => { | |
if (padList[index]) { | |
return item.padStart(padList[index], ' '); | |
} | |
throw new Error(`No padding specified at index ${index}`); | |
}) | |
.join(','); | |
}; | |
fs.writeFileSync('./padded.csv', parsedCSV.map(padByIndex(padList)).join('\n')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment