Created
September 19, 2022 16:57
-
-
Save caprica/84c148180a620f43abc736e51818fcab to your computer and use it in GitHub Desktop.
Rita, Markov and Typescript
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
/* | |
* No Typescript types for Rita, so: | |
* | |
* 1. Add module declaration, e.g. in a file called "decls.d.ts": | |
* | |
* declare module 'rita'; | |
* | |
* 2. adjust include path in tsconfig.json: | |
* | |
* "include": ["src", "decls.d.ts"], | |
* | |
* 3. When running via ts-node in Visual Studio code, change tsconfig.json to add: | |
* | |
* "ts-node": { | |
* "files": true | |
* } | |
*/ | |
import fs from 'fs' | |
import rita from 'rita' | |
/** | |
* A simple class that wraps a Rita Markov generator. | |
*/ | |
class TextGenerator { | |
private readonly markov | |
/** | |
* Create a text generator. | |
* | |
* @param elements n-factor | |
* @param source source filename containing the text corpus | |
*/ | |
constructor(elements: number, source: string) { | |
this.markov = rita.markov(elements) | |
this.markov.addText( | |
fs.readFileSync(source, { encoding: 'utf-8', flag: 'r' }) | |
) | |
} | |
/** | |
* Generate gibberish. | |
* | |
* @param sentences number of sentences to generate | |
* @returns gibberish | |
*/ | |
generate(sentences: number) { | |
return this.markov.generate(sentences) | |
} | |
} | |
// Create an instance | |
const myTextGenerator = new TextGenerator(3, 'some-file-with-text-in-it.txt') | |
// Test it... | |
console.log(myTextGenerator.generate(3)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment