weighted-markov-generator
Version:
Quick and simple to use weighted markov text generator, seed with any text
66 lines (65 loc) • 2.39 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.WeightedMarkovGenerator = void 0;
const seedDictionary_1 = require("./seedDictionary");
class WeightedMarkovGenerator {
constructor(seedLength = 4) {
this.seedLength = seedLength;
this.seedDictionary = new seedDictionary_1.SeedDictionary(seedLength);
}
// Reset seed length, this forgets all seed text
setSeedLength(seedLength) {
this.seedLength = seedLength;
this.seedDictionary = new seedDictionary_1.SeedDictionary(this.seedLength);
}
seedText(text) {
this.seedDictionary.populateDictionary(text);
}
generateText(textLength, start = "", endsOn = "") {
if (endsOn.length > this.seedLength) {
throw new Error("endsOn length cannot exceed seed length");
}
if (endsOn != "" && !this.seedDictionary.hasSeed(endsOn)) {
throw new Error("endsOn are not in the seed files, cannot end on phrase provided");
}
if (start == "") {
start = this.seedDictionary.getRandomSeed();
}
let currLength = start.length;
let currText = start;
while (true) {
let csl = this.seedLength;
if (csl > currText.length) {
csl = currText.length;
}
let seedFound = false;
while (csl >= 1) {
let seed = currText.slice(-csl);
if (this.seedDictionary.hasSeed(seed)) {
let val = this.seedDictionary.getValue(seed);
currText += val;
seedFound = true;
break;
}
csl--;
}
if (!seedFound) {
// Unable to find seed, returning a truncated version.
return currText;
}
// Process endsOn
if (currText.length >= textLength) {
if (endsOn.length > 0) {
if (currText.length >= 2 * textLength) {
return currText;
}
if (endsOn != currText.slice(-endsOn.length)) {
continue;
}
}
return currText;
}
}
}
}
exports.WeightedMarkovGenerator = WeightedMarkovGenerator;