Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rough draft of a HN Markov generator.
var mysql = require('mysql');
var connection = mysql.createConnection({
user : 'root',
password : 'root',
database : 'hnmarkov'
});
Array.prototype.random = function () {
return this[Math.floor(Math.random() * this.length)];
};
connection.connect();
var memory = {}
, learnTitle = function (txt) {
// Clean up the text a bit, English is weird.
txt = txt.title.toLowerCase().replace(/[:,.!?()'"]/g, '');
var parts = txt.split(' ')
, prev = ''; //beginning-of-word
parts.reduce(learnLetter, memory);
function learnLetter (mem, letter) {
if (!mem[prev]) {
mem[prev] = [];
}
mem[prev].push(letter);
prev = letter;
return mem;
};
}
, generate = function(lastWord) {
var currentChoices = memory [(lastWord || '')];
if (!currentChoices) return '.';
var current = currentChoices.random();
return current + ' ' + generate(current);
};
connection.query('SELECT title FROM stories', function(err, rows, fields) {
if (err) throw err;
rows.forEach(learnTitle);
console.log(generate());
connection.end();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment