Skip to content

Commit

Permalink
Refactor helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
cressie176 committed Jan 7, 2024
1 parent c31e1ab commit d6cb663
Showing 1 changed file with 54 additions and 36 deletions.
90 changes: 54 additions & 36 deletions lib/helpers.js
Original file line number Diff line number Diff line change
@@ -1,43 +1,61 @@
const fs = require('fs');
const fs = require('node:fs');
const Papa = require('papaparse');

module.exports = {
tableName: (name, version) => `${name.toLowerCase().replace(/\s/g, '_')}_v${version}`,
/* eslint-disable no-param-reassign */
loadCsv: (path, options) => {
const source = fs.readFileSync(path, 'utf8');
let frames;
Papa.parse(source, {
header: true,
dynamicTyping: true,
skipEmptyLines: true,
complete: (results) => {
frames = results.data.map((data) => {
const action = data.action;
delete data.action;
Object.keys(data).forEach((key) => {
if (data[key] === null) delete data[key];
});
return { action, data };
});
},
error: (err) => {
throw err;
},
});
return frames.reduce((output, frame) => {
return output + options.fn(frame);
}, '');
},
/* eslint-enable no-param-reassign */
xkeys: (obj, options) => Object.keys(obj).reduce(toString.bind(options), ''),
xvalues: (obj, options) => Object.values(obj).reduce(toString.bind(options), ''),
and(...args) {
return args.every(Boolean);
},
};
function tableName(name, version) {
return `${name.toLowerCase().replace(/\s/g, '_')}_v${version}`;
}

function loadCsv(path, options) {
const rows = parseCsv(path);
const frames = rows.map((row) => {
const data = Object.keys(row)
.filter((key) => key !== 'action')
.filter((key) => row[key] !== null)
.reduce((obj, key) => {
return { ...obj, [key]: row[key] };
}, {});
return { action: row.action, data };
});

return frames.reduce((output, frame) => {
return output + options.fn(frame);
}, '');
}

function parseCsv(path) {
const source = fs.readFileSync(path, 'utf8');
const { data } = Papa.parse(source, {
header: true,
dynamicTyping: true,
skipEmptyLines: true,
error: (err) => {
throw err;
},
});
return data;
}

function xkeys(obj, options) {
return Object.keys(obj).reduce(toString.bind(options), '');
}

function xvalues(obj, options) {
return Object.values(obj).reduce(toString.bind(options), '');
}

function and(...args) {
return args.every(Boolean);
}

function toString(result, item, index, items) {
const context = { item, isLast: index === items.length - 1 };
return result + this.fn(context);
}

module.exports = {
tableName,
loadCsv,
xkeys,
xvalues,
and,
};

0 comments on commit d6cb663

Please sign in to comment.