Skip to content

Instantly share code, notes, and snippets.

@sugendran
Created December 2, 2014 08:41
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 sugendran/f622aee2e556a9c44135 to your computer and use it in GitHub Desktop.
Save sugendran/f622aee2e556a9c44135 to your computer and use it in GitHub Desktop.
Node app to read apple financial data and combine them into a single tab separated file
// Assumes all apple data is tab seperated and in the current directory
var fs = require('fs');
var path = require('path');
var cwd = process.cwd();
var contents = fs.readdirSync(cwd);
var _headers = [];
var _data = [];
function parseHeaders (cols) {
for (var i=0, ii=cols.length; i<ii; i++) {
var indx = _headers.indexOf(cols[i]);
if (indx === -1) {
indx = _headers.length;
}
_headers[indx] = cols[i];
}
return cols;
}
function parseRow (headers, cols) {
var row = [];
for (var i=0, ii=cols.length; i<ii; i++) {
var header = headers[i];
var indx = _headers.indexOf(header);
row[indx] = cols[i];
}
return row;
}
function splitByTab (str) { return str.split(/\t/g); }
contents.forEach(function (file) {
if (file.substr(file.length - 4) !== '.txt') {
return;
}
var contents = fs.readFileSync(path.join(cwd, file), { encoding: 'utf8' });
var lines = contents.split(/\n/g);
var headers = splitByTab(lines[0]);
parseHeaders(headers);
for (var i=1, ii=lines.length; i<ii; i++) {
var line = lines[i];
if (line.indexOf('Total_Rows') !== -1) {
return;
}
var row = parseRow(headers, splitByTab(line));
_data.push(row);
}
});
console.log(_headers.join('\t'));
_data.map(function (row) {
console.log(row.join('\t'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment