Created
November 5, 2018 21:16
-
-
Save earthboundkid/47849fbde5895c40742a42e1a38dc561 to your computer and use it in GitHub Desktop.
Simple Markov text generator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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