Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple Markov text generator
class Markov {
constructor(text) {
text = text.replace(/\./g, " . ");
text = text.replace(/\s\s+/g, " ");
this.map = {};
let w1 = "";
let w2 = "";
text.split(/\s/).forEach(w3 => {
if (!this.map[w1 + " " + w2]) this.map[w1 + " " + w2] = [];
this.map[w1 + " " + w2].push(w3);
w1 = w2;
w2 = w3;
if (w3 == ".") {
w1 = "";
w2 = "";
}
});
}
nextWord(w1, w2) {
let choices = this.map[w1 + " " + w2];
if (!choices) {
return "";
}
let index = Math.floor(Math.random() * choices.length);
return choices[index];
}
get sentence() {
for (let i = 0; i < 100; i++) {
let w1 = "";
let w2 = "";
let words = [];
while (true) {
let w3 = this.nextWord(w1, w2);
if (!w3 || w3 == ".") {
break;
}
words.push(w3);
w1 = w2;
w2 = w3;
}
if (words.length > 4 && words.join(" ").length < 140)
return words.join(" ") + ".";
}
return "ERROR: Could not generate sentence."
}
fill(querySelector) {
let el = document.querySelector(querySelector);
el.innerText = this.sentence;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.