Skip to content

Instantly share code, notes, and snippets.

@heatherbooker
Last active December 3, 2016 03:08
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 heatherbooker/a5f0961bb9aad7b5ad0271e00f96f5d0 to your computer and use it in GitHub Desktop.
Save heatherbooker/a5f0961bb9aad7b5ad0271e00f96f5d0 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const tsvFileName = process.argv[2];
const tsvFile = fs.readFileSync(tsvFileName, 'utf8');
const lines = tsvFile.split('\n');
const headings = lines[0].split('\t');
function addWord(word, obj) {
// Update min
if (obj.min === null) {
obj.min = word;
} else if (word < obj.min) {
obj.min = word;
}
// Update max
if (obj.max === null) {
obj.max = word;
} else if (word > obj.max) {
obj.max = word;
}
// Update the full column!
obj.values.push(word);
}
// Initialize list of columns
const columns = [];
headings.forEach(h => {
columns.push({
'min': null,
'max': null,
'values': [],
'heading': h
});
});
const rows = lines.slice(1);
rows.forEach((line, i) => {
const words = line.split('\t');
words.forEach((word, index) => {
var obj = columns[index];
addWord(word, obj);
});
});
function offerHelp(prefix, suffix) {
prefix && console.log(prefix);
console.log('\nColumns:', headings);
console.log('\nCommands:\n max <column>\n min <column>\n search <column> <search_term>\n help\n');
suffix && console.log(suffix);
}
function search(column, search_term) {
return column.values.includes(search_term) ? 'Value was found' : 'Value not found :(';
}
offerHelp('What would you like to know?');
rl.on('line', input => {
try {
if (input.trim() === 'help') {
offerHelp();
} else {
const command = input.split(' ')[0].trim();
const columnName = input.split(' ')[1].trim();
const column = headings.indexOf(columnName);
let result;
if (command === 'search') {
result = search(column, input.split(' ')[2].trim());
} else {
result = columns[column][command];
}
console.log(result);
}
} catch (e) {
console.log('That was not a valid option, please try again.');
}
rl.setPrompt('\nWhat would you like to know? (Type "help" for options)\n');
rl.prompt();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment