Skip to content

Instantly share code, notes, and snippets.

@Grohden
Created February 25, 2022 18:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Grohden/d094d6b52bbd7dffce29673370e60420 to your computer and use it in GitHub Desktop.
Save Grohden/d094d6b52bbd7dffce29673370e60420 to your computer and use it in GitHub Desktop.
Script to pad CSV columns (for readability)
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