feat: add Markov chain-based made-up word generation tool
This commit is contained in:
29
services/makeUpWords.ts
Normal file
29
services/makeUpWords.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
import { buildMarkovChain, generateWordFromChain, type MarkovOptions } from "@/helpers/markov"
|
||||
|
||||
export const generateMadeUpWords = (words: string[], count: number, options: MarkovOptions = {}): string[] => {
|
||||
const { minLength, maxLength, order = 2, startWith, maxAttempts = 1000 } = options
|
||||
|
||||
// If no words provided, return empty array
|
||||
if (words.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
// Calculate min/max lengths from dictionary if not provided
|
||||
const lengths = words.map((w) => w.length)
|
||||
const actualMinLength = minLength ?? Math.min(...lengths)
|
||||
const actualMaxLength = maxLength ?? Math.max(...lengths)
|
||||
|
||||
// Build Markov chain
|
||||
const chain = buildMarkovChain(words, order, startWith)
|
||||
|
||||
// Generate the requested number of words
|
||||
const result: string[] = []
|
||||
for (let i = 0; i < count; i++) {
|
||||
const word = generateWordFromChain(chain, actualMinLength, actualMaxLength, maxAttempts)
|
||||
if (word) {
|
||||
result.push(word)
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
Reference in New Issue
Block a user